我正在尝试使用扫描仪输入学生详细信息,但我一直收到此错误:
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;
}
}
}
答案 0 :(得分:5)
问题是您将Scanner
个对象传递给addStudent
方法,而不是从扫描仪获取的字符串:
app.addStudent(name, DOB, address, gender);
应该是
app.addStudent(Name, DOB, Address, Gender);
此外:
Scanner
对象就足够了。不需要四个。gender
而不是Gender
。将所有内容放在一起,您的代码应如下所示:
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....");
答案 1 :(得分:1)
您只需要一台扫描仪,而不是每台输入一台扫描仪。
在您的代码中,您将Name
(字符串)与name
(扫描仪)混淆。
这就是为什么有命名规则。
尝试更改为
Scanner input = new Scanner (System.in);
String name = input.nextLine ();
String gender = input.nextLine ();
...
然后
app.addStudent (name, dob, address, gender);
还尝试阅读naming conventions
答案 2 :(得分:0)
名称,地址和性别是扫描仪,您的方法采用字符串
app.addStudent(Name, DOB, Address, Gender);
是使用您定义的String变量的方法