我遇到了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