我遇到了Scanner的问题,因为它似乎采用了输入值类型,并强制下次用户输入一个相同类型的值。我找不到任何理由为什么这个代码不起作用,并给我一个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();
}
这个问题不仅适用于register()方法,而且适用于程序范围,例如使用此代码:
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;
}
}
如果其中一个方法,如register需要用户输入一个String,则int user = input.nextInt();将导致InputMismatchException。
答案 0 :(得分:0)
我已经复制了这段代码,但我没有遇到同样的问题。如果用户在提示输入课程编号时输入一个整数(如11),则代码将正常运行。当然,如果输入的内容不是整数,则会抛出InputMismatchException。请参阅Scanner#nextInt()的Java doc description,特别是:
将输入的下一个标记扫描为int。
调用nextInt()形式的此方法的行为与调用nextInt(radix)的方式完全相同,其中radix是此扫描程序的默认基数。
抛出:
InputMismatchException - 如果下一个标记与整数正则表达式不匹配,或者超出范围
如果你想阻止它并且不想处理try-catch,你可以暂停执行,直到给出一个有效的整数。
public static 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?");
//Loop until the next value is a valid integer.
while(!input.hasNextInt()){
input.next();
System.out.println("Invalid class number! Please enter an Integer.");
}
int section = input.nextInt();
input.close();
System.out.println(course_name + " " + section);
}