本文共 1948 字,大约阅读时间需要 6 分钟。
我正在尝试使用扫描仪输入学生详细信息,但我不断收到此错误:
error: incompatible types: Scanner cannot be converted to String
我有4个扫描仪
static Scanner name = new Scanner(System.in);
static Scanner Date = new Scanner(System.in);
static Scanner address = new Scanner(System.in);
static Scanner gender = new Scanner(System.in);
我的代码如下
System.out.println("You have chosen to add a student. Please enter the following details");
System.out.println("Name: ");
String Name = name.nextLine();
System.out.println("DOB: ");
String DOB = Date.nextLine();
System.out.println("Address: ");
String Address = address.nextLine();
System.out.println("Gender: ");
String Gender = gender.nextLine();
app.addStudent(name, DOB, address, gender);
System.out.println(Name + " has been added!" + "\n" + "Returning to menu....");
app.delay();
addStudent方法如下
public void addStudent (String name,String DOB,String address,String gender)
{
for(int i = 0; i < enrolment.length; i++)
{
if (enrolment[i] == null)
{
this.enrolment[size] = new Student(name, DOB, address, gender);
this.size++;
if (gender == "Male")
{
this.maleStudents++;
}
else {
this.femaleStudents++;
}
break;
}
}
}
解决方法:
问题是您将Scanner对象传递给addStudent方法而不是从扫描仪获取的字符串:
app.addStudent(name, DOB, address, gender);
应该
app.addStudent(Name, DOB, Address, Gender);
也:
>一个Scanner对象就足够了.不需要四个.
> Java代码约定规定变量名称在较低的驼峰情况下,即性别而不是性别.
将所有内容放在一起,您的代码应如下所示:
Scanner scanner = new Scanner(System.in);
System.out.println("You have chosen to add a student. Please enter the following details");
System.out.println("Name: ");
String name = scanner.nextLine();
System.out.println("DOB: ");
String dob = scanner.nextLine();
System.out.println("Address: ");
String address = scanner.nextLine();
System.out.println("Gender: ");
String gender = scanner.nextLine();
app.addStudent(name, dob, address, gender);
System.out.println(name + " has been added!" + "\n" + "Returning to menu....");
标签:java,arrays,java-util-scanner
来源: https://codeday.me/bug/20190528/1170831.html
转载地址:http://eycpo.baihongyu.com/