在这里,我试图输入并打印一些员工的详细信息,一切看起来都不错,但我得到了一个例外原因?
import java.util.Scanner;
class EmpDet
{ //here details
int age;
String name;
int ssn;
public EmpDet(int age,String name,int ssn)
{
//assign to constructor
this.age = age;
this. name = name;
this.ssn = ssn;
System.out.println(age+" "+name+" "+ssn); //printing details
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine(); //InputMismatchException in this line
int ssn = sc.nextInt();
EmpDet det = new EmpDet(age,name,ssn);
}
}
答案 0 :(得分:1)
您可能希望逐行抓取。获得该行后,您可以尝试将输入解析为整数。
Scanner sc = new Scanner(System.in);
int age = Integer.parseInt(sc.nextLine());
String name = sc.nextLine();
int ssn = Integer.parseInt(sc.nextLine());
EmpDet det = new EmpDet(age,name,ssn);
如果来自用户的输入不符合整数,那么在解析时设置try catch也是明智的。
注意,nextInt()只抓取数字而不是新行(输入)