2017-08-04 96 views
0

爲什麼不是按預期方式工作?While循環掃描器

public class FinalTest { 
    public static void main (String [] args) { 

    Scanner in = new Scanner(System.in); 
    int k = 0; 

    boolean askForInput = true; 

    while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
     k = in.nextInt(); 
     askForInput = false; 
     } catch (InputMismatchException e) { 
     System.out.println("ERR: Not an integer!!"); 
     } 
    } 

    } 
} 

nextInt()嘗試掃描輸入作爲一個int,如果它不是一個整數,它應該拋出一個異常錯誤:不是整數。什麼錯誤是我爲什麼不提示再次輸入?它只是在屏幕上繼續打印ERR消息。

+2

嘗試添加''in.nextLine();''後打印錯誤消息 –

+0

@mondoteck工作!謝啦! – py9

回答

0

這是正確的表格,你應該重新開始循環:

一個你可以看到,我把System.out.print("Enter an integer: "); ,使其不reduntant。

public static void main(String[] args){ 
      System.out.print("Enter an integer: "); 
      Scanner in = null; 
      int k = 0; 

      boolean askForInput = true; 

      while (askForInput) { 

       in = new Scanner(System.in); 
       try { 
       k = in.nextInt(); 
       askForInput = false; 
       } catch (InputMismatchException e) { 
       System.out.println("ERR: Not an integer!!"); 
       askForInput = true; 
       System.out.print("Enter an integer: "); 

       } 
      } 
      System.out.print("End"); 

      } 
     } 

輸出:

enter image description here

0

documentation of nextInt

此方法將拋出InputMismatchException如果如下面描述的下一個標記不能被轉換爲有效的int值。 如果翻譯成功,則掃描儀前進超過匹配的輸入。

換句話說,nextInt離開令牌流中的令牌,如果它不被識別爲一個數字。一個修復可能是使用next()丟棄catch塊中的令牌。

2

如果不是整數,nextInt()調用不會消耗您的輸入(例如「abc」)。所以下一次在循環中它仍然會看到你已經進入的「abc」,並且這種情況會一直持續下去。所以最好使用的Integer.parseInt(in.next()):

public static void main (String [] args) { 

    Scanner in = new Scanner(System.in); 
    int k = 0; 

    boolean askForInput = true; 

    while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
      k = Integer.parseInt(in.next()); 
      askForInput = false; 
     } catch (NumberFormatException e) { 
      System.out.println("ERR: Not an integer!!"); 
     } 
    } 
} 
+0

這是有道理的。但爲什麼不打印「輸入一個整數」呢?因爲這是循環的開始 – py9

+0

@ py9它爲我打印它。仔細檢查你的代碼(如果它是在編譯/執行之前保存的),並確保你使用的是在這裏發佈的解決方案。 – Pshemo

+0

我的不好。工作正常。謝謝! – py9

0

當執行try塊,askForInput是越來越更改爲false,無論k結束你在第一次循環,每次循環的價值。試試這個:

while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
     k = in.nextInt(); 
     askForInput = false; 
     } catch (InputMismatchException e) { 
     System.out.println("ERR: Not an integer!!"); 
     askForInput = true; //add this line resetting askForInput to true 
     } 
    } 
+0

但如果它更改爲false不會退出循環嗎? – py9