1

我对这段代码的问题如下:变量号不能是一个字符串,所以我尝试使用try,catch(InputMissmatchException)语句来处理这个问题。但是,当进入循环并且有人输入一个字符串时,异常是句柄,但是它会使用最后一个有效条目再次循环。即我输入5,然后输入“hello”,结果是:“您必须输入一个数字。”但是现在5再次被计数。在while循环中的异常处理

这使计数器添加一个太多的计数变量。如果用户继续使用字符串,则循环会一直添加最后一个有效条目,因此计数在最后会错误。

从逻辑上讲,我希望程序处理问题并要求用户输入正确的条目,直到输入可接受的整数,而不再通过while循环;当用户输入有效的条目时,保持循环或存在(-1)。

int number = 0; 
int[] count = new int[11]; 

    try 
     { 
     number = input.nextInt(); 
     } 
     catch (InputMismatchException y) 
     { 
     System.out.println("You must enter a number."); 
     input.nextLine(); 

     }  


    while (number != -1) 
    { 
     try 
     { 
      ++count[number]; 
     } 
     catch (IndexOutOfBoundsException e) 
     { 
      System.out.println("Please enter a valid number from the menu."); 
     } 

     try 
     { 
     number = input.nextInt(); 
     } 
     catch (InputMismatchException y) 
     { 
     System.out.println("You must enter a number."); 
     input.nextLine(); 

     } 
    } 

回答

1

听起来像是你想有一个while循环,直到他们进入一些

int number = 0; 
int[] count = new int[11]; 

while(true) { 
    try 
    { 
    number = input.nextInt(); 
    break; 
    } 
    catch (InputMismatchException y) 
    { 
    System.out.println("You must enter a number."); 
    input.nextLine(); 

    } 
} 


while (number != -1) 
{ 
    try 
    { 
     ++count[number]; 
    } 
    catch (IndexOutOfBoundsException e) 
    { 
     System.out.println("Please enter a valid number from the menu."); 
    } 

    while(true) { 
     try 
     { 
      number = input.nextInt(); 
      break; 
     } 
     catch (InputMismatchException y) 
     { 
      System.out.println("You must enter a number."); 
      input.nextLine(); 
     } 
    } 

}