2017-09-25 83 views
1

我在這方面遇到了很多麻煩。我嘗試過多種方式,但它仍然給我一個錯誤信息和崩潰。我想循環播放,直到用戶輸入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) 
+0

使用'next'而不是'nextInt'添加'try/catch'來處理'NumberFormatException'...(顯然使用'if'來檢查它是1還是2) – Idos

+0

@Idos謝謝!我爲什麼要用if語句?它不像循環一樣循環。我不希望它停止要求用戶輸入1或2. – sukiyo

+0

我的意思是使用'if' _inside_循環。 – Idos

回答

2

使用nextLine而不是nextInt,事後有例外處理。

boolean accepted = false; 
do { 
    try { 
     listChoice = Integer.parseInt(scan.nextLine()); 
     if(listChoice > 3 || listChoice < 1) { 
      System.out.println("Choice must be between 1 and 2!"); 
     } else { 
      accepted = false; 
     } 
    } catch (NumberFormatException e) { 
     System.out.println("Please enter a valid number!"); 
    } 
} while(!accepted); 
+0

非常感謝你!我認爲這是一個非常棒的思考過程。我也想邏輯思考,但我只是一個初學者,我覺得很愚蠢。在else語句中我相信accepted = true。如果我把它當作虛假的,它會一直爲我循環。而且我也相信這是if(listChoice> = 3 || listChoice <1) – sukiyo

+0

當我輸入一個字母時,它仍然給我帶來麻煩。我改變它捕捉(InputMismatchException e),但它仍然說我有InputMismatchException錯誤。 – sukiyo

1

你也可以在Switch Case語句中試試這個。

switch(listchoice) 
{ 
    case 1: 
    //Statment 
    break; 

    case 2: 
    //statement 
    break; 

    default: 
    System.out.println("Your error message"); 
    break; 
} 
1

因爲用戶可以輸入任何東西,你有一個線作爲字符串讀取:

String input = scan.nextLine(); 

一旦你做到了這一點,測試很簡單:

input.matches("[12]") 

All together:

String input = null; 
do { 
    System.out.println("Enter either 1 or 2:"); 
    input = scan.nextLine(); 
} while (!input.matches("[12]")); 

int listChoice = Integer.parseInt(input); // input is only either "1" or "2" 
+0

這是一個有趣的方法!我也會嘗試一下!謝謝你! – sukiyo

相關問題