【发布时间】:2017-02-17 07:40:19
【问题描述】:
我在使用 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;
}
}
如果注册方法之一需要用户输入字符串,则 int user=input.nextInt();将导致 InputMismatchException。
【问题讨论】:
标签: java java.util.scanner inputmismatchexception