2017-09-30 30 views
-3

對於我的任務之一,我們應該嘗試捕獲一個InputMismatchException並告訴用戶輸入一個給定的選項(在這種情況下,它可以是1,2,3,4而沒有其他)。出於某種原因,每當我嘗試創建try catch塊時,它都會讓用戶輸入兩次輸入,並且仍然會使程序崩潰。這裏是我有:如何使用try catch java?

do { 
     Scanner menuOptions = new Scanner(System.in); 
     System.out.println("1. Get another card"); 
     System.out.println("2. Hold hand"); 
     System.out.println("3. Print statistics"); 
     System.out.println("4. Exit"+ "\n"); 
     System.out.println("Choose an Option: "); 
     int selectedOption = menuOptions.nextInt(); 

     try{ 
     selectedOption = menuOptions.nextInt(); 
     } 

     catch(InputMismatchException e){ 
     System.out.println("Invalid input! Please select between options 1,2,3,4") 
     } 


     if (selectedOption == 1) { 
     //proceeds to do what is instructed if user input is 1} 
     else if (selectedOption ==2{ 
     //proceeds to do what is instructed if user input is 2} 
    else if (selectedOption == 3) { 
     //proceeds to do what is instructed if user input is 3} 
    else if (selectedOption ==4{ 
     //proceeds to do what is instructed if user input is 4} 

任何想法,我怎麼能使這項工作?

+0

[看看這個答案]( https://stackoverflow.com/questions/12702076/java-try-catch-with-inputmismatchexception-creates-infinite-loop) 希望這會有所幫助! –

回答

0

「進入輸入兩次」

因爲你有兩行要求的數字:

menuOptions.nextInt(); 
1

這是因爲你叫menuOptions.nextInt()兩次。初始化完成後,第二次在try catch塊中。我假設你有你想要運行,直至用戶輸入有效輸入代碼,是1,2,3或4

試試這個:

int selectedOption; 
while(true) { 
    try { 
     selectedOption = menuOptions.nextInt(); 
     break; 
    } catch(InputMismatchException ime) { 
     System.out.println("Invalid input! Please select between options 1,2,3,4"); 
     menuOptions = new Scanner(System.in); 
    } 
} 
+0

對不起,你可以向我解釋這一點,我有點失落。我嘗試了你說的話,但程序仍然崩潰。 – Peter

+0

@Peter你介意發佈堆棧跟蹤嗎? – Ryan