我在這方面遇到了很多麻煩。我嘗試過多種方式,但它仍然給我一個錯誤信息和崩潰。我想循環播放,直到用戶輸入1或2如何將用戶輸入限制爲整數1或2,並且不允許用戶在java中輸入除整數以外的任何內容?
System.out.println("Please choose if you want a singly-linked list or a doubly-linked list.");
System.out.println("1. Singly-Linked List");
System.out.println("2. Doubly-Linked List");
int listChoice = scan.nextInt();
//Restrict user input to an integer only; this is a test of the do while loop but it is not working :(
do {
System.out.println("Enter either 1 or 2:");
listChoice = scan.nextInt();
} while (!scan.hasNextInt());
它給我這個錯誤:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.main(Main.java:35)
使用'next'而不是'nextInt'添加'try/catch'來處理'NumberFormatException'...(顯然使用'if'來檢查它是1還是2) – Idos
@Idos謝謝!我爲什麼要用if語句?它不像循環一樣循環。我不希望它停止要求用戶輸入1或2. – sukiyo
我的意思是使用'if' _inside_循環。 – Idos