因此,我试图计算一个简单程序,该程序具有n个类型为Person的对象,每个人都有一个姓名,身份证,护照和驾驶执照。
它是这样的:
public class Person {
private String name;
private int id;
private int passport;
private int licence;
Person(String name, int id, int passport, int licence) {
this.name=name;
this.id=id;
this.passport=passport;
this.licence=licence;
}
}
public class Main {
public static void main(String[] args) {
Scanner jin=new Scanner(System.in);
int n=jin.nextInt(), i;
Person[] dudes=new Person[n];
for(i=0; i<n; i++) {
String name=jin.nextLine();
int id=jin.nextInt();
int passport=jin.nextInt();
int licence=jin.nextInt();
dudes[i]=new Person(name, id, passport, licence);
}
}
}
但是,当我输入字符串名称的值时,会出现以下错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.Main.main(Main.java:20)
有任何想法吗?
最佳答案
如果将String name = jin.nextLine();
更改为String name = jin.next();
,则如何使用它。
一种更简单的方法是在键入int后对名字和姓氏进行清除,从而清除缓冲区。
for(i=0; i<n; i++)
{
jin.nextLine(); // add this to clear the input from before.
String name=jin.nextLine();
int id=jin.nextInt();
int passport=jin.nextInt();
int licence=jin.nextInt();
dudes[i]=new Person(name, id, passport, licence);
}