while循环中的异常处理

Exception Handling in a while loop

我在这段代码中遇到的问题如下:变量号不能是字符串,所以我尝试使用 try, catch (InputMissmatchException) 语句来解决这个问题。但是,当 in 进入循环并且有人输入字符串时,异常被处理但它使用最后一个有效条目再次通过循环。即我输入 5 然后我输入 "hello" 结果是:"You must enter a number." 但现在又计算了 5。

这会使计数器向计数变量加一过多。如果用户继续使用字符串,循环会不断添加最后一个有效条目,因此最后的计数将是错误的。

从逻辑上讲,我希望程序能够处理该问题并要求用户输入正确的条目,直到输入可接受的整数为止,而无需再次通过 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();

        } 
    }

听起来你想要一个 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();
        } 
    }

}