我遇到了Scanner问题,因为它似乎正在接受输入值类型,并强制下次用户输入的值为相同类型。我无法找到任何原因,为什么这段代码不工作,并给我一个InputMismatchException,因为我写了这样的代码一百万次,没有问题。找不到InputMismatchException的原因
public void register(){
Scanner input=new Scanner(System.in);
System.out.println("What course would you like to register for?");
String course_name = input.next();
System.out.println("What section?");
int section = input.nextInt();
for (int i = 0; i < courses.size(); i++) {
if (courses.get(i).getCourse_name().equals(course_name)) {
if (courses.get(i).getCourse_section() == section) {
courses.get(i).AddStudent(this.first_name+" "+this.last_name);
}
}
}
input.close();
}
此问题是不只是为寄存器()方法,但计划范围,例如具有这样的代码:
public void Options() {
Scanner input=new Scanner(System.in);
while (true) {
System.out.println("What would you like to do (Enter corresponding number):" + "\n" + "1) View all courses" + "\n" + "2) View all courses that are not full" + "\n" + "3) Register on a course" + "\n" + "4) Withdraw from a course" + "\n" + "5) View all courses that the current student is being registered in" + "\n" + "6) Exit");
int user = input.nextInt();
if (user == 1)
viewAll();
if (user == 2)
viewAllOpen();
if (user == 3)
register();
if (user == 4)
withdraw();
if (user == 5)
viewRegistered();
if (user == 6) {
Serialize();
break;
}
}
如果的方法中,如寄存器中的一个需要用户输入一个String,int user = input.nextInt();将导致InputMismatchException。
检查http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – TheLostMind