Do - while goes into an infinite loop

不羁岁月 提交于 2020-02-23 07:16:08

问题


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.

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

回答1:


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



回答2:


Put

sc.nextLine();

next

x = sc.nextInt();



来源:https://stackoverflow.com/questions/60014004/do-while-goes-into-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!