做-进入无限循环 [英] Do - while goes into an infinite loop

查看:91
本文介绍了做-进入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向此菜单添加输入验证.当用户输入例如:"a"或非整数且具有给定范围的任何输入时,它必须执行catch块并再次循环以提示用户再次输入,但取回一次输入后它将保持无限循环.因此,它从执行菜单到跳过输入部分并执行catch块.

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. So it goes from executing the menu and just skipping over the input part and executes the catch block.

如果我输入的不是整数,它将进入无限循环.

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);

推荐答案

问题是,当扫描程序获取字符/字符串而不是int时,您没有刷新缓冲区.另外,如果在第一次迭代中读入一个字符/字符串,则循环将终止,因为循环条件将返回false,且x最初设置为1.您可以通过将其设置为-1来解决此问题.此外,您可以使用hasNextInt()方法来检查用户是否输入int,而不是使用try catch块.

The issue is that you are not flushing the buffer when the Scanner gets a character/string instead of an 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. 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.

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();

这篇关于做-进入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆