简体   繁体   中英

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

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

Put

sc.nextLine();

next

x = sc.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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