无限循环;不明白怎么回事



在下面的代码中,当我输入整数值以外的任何值时,代码不会再次要求输入,而是无限循环字符串输出。一点帮助。。。

    int choice = 0;
    while(choice == 0)
    {
        try
        {
            System.out.println("Start by typing the choice number from above and hitting enter: ");
            choice = input.nextInt();
        }
        catch(Exception e)
        {
        }
        if ((choice == 1) || (choice == 2) || (choice == 3))
        {
            break;
        }
        else
        {
            System.out.println("Invalid choice number. Please carefully type correct option.");
            choice = 0;
        }
    }

当您输入一个非整数时,它将不会被消耗。您需要扫描它。例如,可以通过将input.nextLine()语句添加到catch块来完成。这将消耗无效的输入,并允许您的程序读取新数据。

这将解决您的问题:

catch(Exception e)
{
    input.nextLine(); // Consume the invalid line
    System.out.println("Invalid choice number. Please carefully type correct option.");
}

您也可以将行读取为字符串,并尝试使用Scanner.nextLineInteger.parseInt将其解析为数字,但我更喜欢使用nextInt来表示整数。它使代码的目的更加明确(在我看来)。

当使用nextInt并且下一个输入不是int时,它将抛出异常,但不会消耗数据,即下一个调用将立即返回,因为数据仍然存在。

您可以通过使用类似[^0-9]*的模式调用skip方法来跳过所有无效输入来解决此问题。然后像"aaa3"这样的输入就可以工作了。若要忽略所有内容,请使用.*作为模式。

问题是您没有消耗流中的剩余数据。我用以下代码解决了这个问题,尽管在程序中使用它之前,你会想更好地记录你的代码:

int choice = 0;
while(choice == 0)
{
    try
    {
        System.out.print("Start by typing the choice number from above and hitting enter: ");
        choice = input.nextInt();
    }
    catch(Exception e)
    {
        input.next();
        System.out.println("Invalid choice number. Please carefully type correct option.");
    }
    if ((choice == 1) || (choice == 2) || (choice == 3))
    {
        break;
    }
    choice = 0;
}

您可以简化和减少代码,如下所示:

    int choice;
    System.out.println("Start by typing the choice number from above and hitting enter: ");
    while(true)
    {
        try {
            choice = input.nextInt();
            if ((choice == 1) || (choice == 2) || (choice == 3))
                break;
        } catch(InputMismatchException e) {  // handle only the specific exception
            input.nextLine();                // clear the input
        }
    System.out.println("Invalid choice number. Please carefully type correct option.");
    }

是否使用import java.util.Scanner;包中的Scanner(system.in);?尝试在catch中添加input.nextLine();以清除该值,从而停止无限循环。

public static void main(String[] args) {
int choice = 0;
Scanner input = new Scanner(System.in);
while(choice == 0)
{
    try
    {
        System.out.println("Start by typing the choice number from above and hitting enter: ");
        choice = input.nextInt();
    }
    catch(Exception e)
    {
        input.nextLine();
        System.out.println("Invalid choice number. Please carefully type correct option.");
    }
    if ((choice == 1) || (choice == 2) || (choice == 3))
    {
        break;
    }
    else
    {
        System.out.println("Invalid choice number. Please carefully type correct option.");
        choice = 0;
    }
 }
}

choice = input.nextInt();行中看起来选项值始终为0。打印选择之后不久。

此外,对于非整数值,添加一个条件以中断循环。

最新更新