0

so I was trying to make a menu with a scanner like this:

   import java.util.Scanner;

   public class Test{

   public static void main(String[] args){

   int menu = 0;
   String roomType;
   Scanner sc = new Scanner(System.in);
   while ( menu != 2 ) {
       System.out.println("MoTel");
       System.out.println("=====");
       System.out.println("1. Book a room");
       System.out.println("2. Exit");
       System.out.print(">> ");
       menu = sc.nextInt();
        
       switch (menu) {
           case 1: 
               do {
                   System.out.print("Insert Room Type [Single | Double | King]: ");
                   roomType = sc.nextLine();
               } while ( !roomType.equals("Single") && !roomType.equals("Double") && !roomType.equals("King") );
                
               break;
           case 2: 
               break;
           default:
               System.out.println("Please select a valid option");
       }
        
    }
  
  }
  }

However, why do in the output prints the scanner inside the case 1 twice? Output

I also tried to remove the do-while loop inside case 1, however the output turns to be like this: Output 2

  • The first time you call `sc.nextLine()` it just consumes the newline character from the end of the line where you entered `1`. The `nextInt()` doesn't consume the newline. See the duplicate for a more detailed explanation. – Dawood ibn Kareem Apr 09 '22 at 06:22

0 Answers0