简体   繁体   中英

Exception in do while loop

I have this piece of code:

do {
  try {
    input = sc.nextInt();
  }

  catch(Exception e) {
     System.out.println("Wrong input");
     sc.nextLine();
   }
}
while (input < 1 || input > 4);

Right now, if I input 'abcd' instead of integer 1-4, it gives message "Wrong Input" and the program loops, how can I make it so that it also gives "Wrong Input" when I entered integer that doesn't fulfill the boolean (input < 1 || input >4)? So that if I entered 5, it will also give me "Wrong Input".

Add this:

if(input < 1 || input > 4) {
  System.out.println("Wrong input");
}

after input = sc.nextInt();

As of now, your try-catch block is checking if input is an int type. The do-while loop is checking input after it has been entered, so it is useless. The condition must be checked after the user enters what he/she wants. This should fix it:

   do 
   {
        try
        {
            input = sc.nextInt();

            if(input < 1 || input > 4) // check condition here.
            {
                System.out.println("Wrong input");
            }
        }
        catch(Exception e)
        {
            System.out.println("Expected input to be an int. Try again."); // tell user that input must be an integer.
            sc.nextLine();
        }

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

You can also do this:

while (true) {
  try {
    input = sc.nextInt();
    if (input >= 1 && input <= 4) {
      break;
    }
  } catch (Exception e) {
    System.out.println("Wrong input");
  }
  sc.nextLine();
}

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