2013-03-27 100 views
-1

我尝试第一次尝试catch块,并且我想让catch {}块,所以如果它捕获到异常,它将返回到原始try {}块直到用户传入的值有效。Java:初学者异常处理问题

说我有下面的代码:

try{ 
    number=keyboard.nextInt(); 
    } 
catch(InputMismatchException e){ 
    System.out.println("That is not an integer!"); 
    } 

编辑:

我加了一个while循环四周,劝整个事情,所以现在我有以下几点:

boolean check=true; 
    while(check){ 
     try{ 
      System.out.println("hey"); 
      number=keyboard.nextInt(); 
      check=false; 
      } 
     catch(InputMismatchException e){ 
      System.out.println("That is not an integer!"); 
      } 
    } 

当我传入扫描仪键盘的错误值时,由于某种原因,我现在正在出现无限循环。它每次都进入try,但它不会每次调用nextInt()方法。有人知道为什么

+0

好的......说你有以下代码......然后呢? – Daedalus 2013-03-27 20:13:00

+0

你的问题是什么?请说明你的问题! – boomz 2013-03-27 20:15:26

回答

0

原因无限循环:

为什么这是造成一个无限循环的理由是,如果有异常发生的Scanner.nextInt()不会提前扫描仪。

在执行方法keyboard.nextInt()时,如果用户输入非整数并且它直接进入打印某些消息的catch块,则会发生InputMismatchException。由于flag仍然成立,while循环再次执行。由于扫描程序在前一个循环中不是先进的,因此同样的异常再次发生,并转到catch块。重复此过程,并导致一个无限循环

修复:

扫描仪需要,如果InputMismatchException恰好前进。根据程序要求,如果它不是整数,并且等待用户的下一个输入,它可以丢弃扫描器中的当前行。在这种情况下(从catch块)调用Scanner.nextLine()或任何方法。

请参阅下面的修改后的代码,它的工作原理。

while (check) 
    { 
     try 
     { 
      System.out.println("hey"); 
      int number = keyboard.nextInt(); 
      check = false; 
      System.out.println("Number accepted !"); 
     } catch (Exception e) 
     { 
      System.out.println("That is not an integer! - " + keyboard.nextLine()); 
     } 
    } 
4

将整个东西包装在一个while (true)循环中,然后break出来,如果你到达nextInt()之后的行。

6

这样做。

boolean flag = true; 
int number= 0; 
while(flag) 
{ 
    try { 
     number=keyboard.nextInt(); 
     flag = false; 
    } 
    catch (InputMismatchException e1) { 
     System.out.println("That is not an integer!");     
    } 
} 
+0

嗨,我试过你的解决方案,但它没有工作,它不知不觉地继续迭代而不去扫描器的nextInt()方法调用。如果可以,请参阅上面的修改。谢谢。 – Blessoul 2013-03-27 20:39:54

+0

@ user2217183它可能是因为除了InputMismatchException之外的一些错误,你为什么进入无限循环。你有没有初始化'keyboard'。 – 2013-03-27 20:44:45

0
while(true) 
{ 
    try 
    { 
     number = keyboard.nextInt(); 
    } 
    catch(InputMismatchException e) 
    { 
     System.out.println("That is not an integer!"); 
     continue; 
    } 
    break; 
} 
+2

因为我们真的很想念去? – 2013-03-27 20:14:51

+1

虽然在功能上是正确的,但“(真)”通常被认为是不好的做法。请参阅http:// stackoverflow。COM /问题/ 390481/IS-whiletrue坏编程实践 – jazzbassrob 2013-03-27 20:15:46

0

把它放在一个while循环中。

boolean hasnum = false; 
do { 
    try{ 
     number=keyboard.nextInt(); 
     hasnum = true; 
     } 
    catch(InputMismatchException e){ 
     System.out.println("That is not an integer!"); 
     } 
} while (!hasnum)