2017-08-04 88 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