简体   繁体   English

Do - while 进入无限循环

[英]Do - while goes into an infinite loop

Im trying to add an input validation to this menu.我正在尝试向此菜单添加输入验证。 When the user enters eg: 'a' or any input that is not a integer and with the given range, it must execute the catch block and loop again to prompt the user to enter again but instead it keeps looping infinitely after taking the input once.当用户输入例如:'a' 或任何不是整数且具有给定范围的输入时,它必须执行 catch 块并再次循环以提示用户再次输入,但在输入一次后继续无限循环. So it goes from executing the menu and just skipping over the input part and executes the catch block.所以它从执行菜单开始,只是跳过输入部分并执行 catch 块。

Edit: it goes into infinite loop if i input anything that is not an integer.编辑:如果我输入任何不是整数的内容,它就会进入无限循环。

Scanner sc = new    Scanner(System.in);

int x = 1;

do{

try

{

System.out.println("Select option ");

System.out.println("1) Circle ");

System.out.println("2) Rectangle ");

System.out.println("3) Triangle ");

System.out.println("4) Exit ");

x = sc.nextInt();

}

catch(Exception e)

{

System.out.print("Invalid data");

}

}while(x<1 || x>4);

The issue is that you are not flushing the buffer when the Scanner gets a character/string instead of an int.问题是当 Scanner 获取字符/字符串而不是 int 时,您没有刷新缓冲区。 In addition, your loop will terminate if a character/string is read in on the first iteration since your loop condition will return false with x set initially to 1. You can fix this by setting it to -1 instead.此外,如果在第一次迭代时读入字符/字符串,您的循环将终止,因为您的循环条件将返回 false,x 最初设置为 1。您可以通过将其设置为 -1 来解决此问题。 Moreover, instead of using a try catch block, you can use the hasNextInt() method to check if the user is typing in an int or not.此外,您可以使用 hasNextInt() 方法来检查用户是否输入了 int,而不是使用 try catch 块。

Scanner sc = new Scanner(System.in);

int x = -1;
do {
    System.out.println("Select option ");   
    System.out.println("1) Circle ");
    System.out.println("2) Rectangle ");
    System.out.println("3) Triangle ");
    System.out.println("4) Exit ");

    if (sc.hasNextInt())
    {
        x = sc.nextInt();
    }
    else
    {
        System.out.println("Invalid input. Please try again.");

        // Flush the buffer
        sc.nextLine();
    }
} while (x < 1 || x > 4);

sc.close();

Put

sc.nextLine(); sc.nextLine();

next下一个

x = sc.nextInt(); x = sc.nextInt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM