2012-04-07 79 views
1

所以我有这样的代码:如何修复InputMismatchException时

protected void giveNr(Scanner sc) { 
    //variable to keep the input 
    int input = 0; 
    do { 
     System.out.println("Please give a number between: " + MIN + " and " + MAX); 
     //get the input 
     input = sc.nextInt(); 
    } while(input < MIN || input > MAX); 
} 

如果人力投入某事那不是一个整数,说一个字母或一个字符串,程序崩溃,并给出了错误,InputMismatchException。我该如何解决这个问题,以便在输入错误类型的输入时,人们再次被要求输入(并且程序不会崩溃?)

回答

2

您可以捕获InputMismatchException,打印一条错误消息告诉用户出了什么问题,并再次绕过回路:

int input = 0; 
do { 
    System.out.println("Please give a number between: " + MIN + " and " + MAX); 
    try { 
     input = sc.nextInt(); 
    } 
    catch (InputMismatchException e) { 
     System.out.println("That was not a number. Please try again."); 
     input = MIN - 1; // guarantee we go around the loop again 
    } 
while (input < MIN || input > MAX)