Java Wrong User Input Loop until correct

2019-09-06 02:34发布

Thanks for your time.

I have a problem validating the program. I have tried using, While/Switch but it is all the same. The issue is when a user enters the wrong input for example 5, it shows the error and then it lets them type it in again, but if they type in the wrong number again, the program does not validate... I can definitely copy the code again and again within it, but there should be an easier way.

Hope you understand what I am trying to achieve:D

How could I make it so it is a continues loop? Thank you!

// Choosing the right room public static int rooms () {

    int room;

    // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);
    // Displaying a message on the screen
    System.out.println("What room are you in? ");
    // Input
    room = scanner.nextInt();

    if (room==1) {

        roomOne();

    } else if (room==2) {

        roomTwo();

    } else if (room==3) {

        roomThree();

    } else if (room==4) {

        roomFour();

    } else {

        System.out.println("Wrong room number, please enter the room number.");
        room = scanner.nextInt();
    }


    //System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");    


    return room;

} // End Rooms

3条回答
地球回转人心会变
2楼-- · 2019-09-06 03:23
while (true) {
    int room = scanner.nextInt();
    if(room < 1 || room > 4) {
        System.out.println("Wrong room number, please enter the room number.");
        continue;
    }
    break;
}
if (room == 1) 
    roomOne();
else if (room == 2) 
    roomTwo();
else if (room == 3) 
    roomThree();
else if (room == 4) 
    roomFour();

Hope it helps, nevertheless you should read a little more about loops.

查看更多
别忘想泡老子
3楼-- · 2019-09-06 03:25

This is how you should set up a loop for input cleaning:

  1. Define a boolean value and assign a true or false value
  2. Make the while loop run on the boolean value
  3. When input is "clean", set the boolean value to true
查看更多
beautiful°
4楼-- · 2019-09-06 03:39

You are looking for a while loop, something like this.

I use a do ... while to execute the line at least once.

The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.

{
     // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);


   int room;   
   do {
      // Displaying a message on the screen
      System.out.println("What room are you in? ");
      room = scanner.nextInt();
   } while( !isValid(room) );

   ... //if else or switch
}

private boolean isValid(int room){
   if(room > 4 || room  < 1){
       System.out.println("Try again ;)" );
       return false;
   }  else return true;
}

This is a quick code note even test.

查看更多
登录 后发表回答