2016-05-18 163 views
1

我面对java.util.InputMismatchException;inputmismatchexception:进入无限循环?

我赶上InputMismatchException时,但我不明白为什么它会进入无限循环以第一输入错误后,输出继续这样:

enter two integers 
exception caught 

这样下去重复

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int flag = 0; 
    while (flag != 1) { 
     try { 
      System.out.println("enter two integers"); 
      int a = sc.nextInt(); 
      int b = sc.nextInt(); 
      int result = a + b; 
      flag = 1; 
      System.out.println("ans is" + result); 
     } catch (NumberFormatException e) { 
      System.out.println("exception caught"); 
     } catch (InputMismatchException e) { 
      System.out.println("exception caught"); 
     } 
    } 
} 

回答

0

如果按回车键,你需要消耗这个人物太

int a = sc.nextInt(); 
int b = sc.nextInt(); 
sc.nextLine(); 

,那么你可以进入

2 3 <CR> 
+0

@Berger是啊,我不知道OP很希望如何进入他的数据。 –

0

在你的代码,正赶上InputMisMatchException,你只是打印一条消息,这将导致再次将while循环。

 int a = sc.nextInt(); 
     int b = sc.nextInt(); 

当这些线扔你flag=1不会被设置例外,你会在一个无限循环。纠正您的异常处理,并打破循环或通过读取字符串来清除扫描仪输入。

0

您需要清除缓冲区,以便在抛出异常之后对缓冲区nextInt()无效。添加finally块,并调用其内部sc.nextLine()

while (flag != 1) { 
    try { 
     System.out.println("enter two integers"); 
     int a = sc.nextInt(); 
     int b = sc.nextInt(); 
     int result = a + b; 
     flag = 1; 
     System.out.println("ans is" + result); 

    } catch (NumberFormatException e) { 
     System.out.println("exception caught"); 
    } catch (InputMismatchException e) { 
     System.out.println("exception caught"); 
    } finally { //Add this here 
     sc.nextLine(); 
    } 
} 

工作例如:https://ideone.com/57KtFw

+0

虽然这将适用于像'1 2'这样的数据,但它会因为'1 2 3'这样的数据而失败,因为'nextLine()'被放置在'finally'中,这意味着即使不抛出异常也会消耗整行*所以它也会消耗'3',这可能是后期应用程序的有效输入。最好是在catch块中处理每个异常,'finally'部分是针对需要执行的强制任务,无论异常是否被抛出。 – Pshemo