0

I'm practicing switch case & scanner inputs for my final exam. However, I have no idea why the 1st scanner input in case 2 is skipped. Here's my code:

Scanner scanner = new Scanner(System.in);
String list=" 1- A \n 2- B \n 3- quit \n Enter your choice";
System.out.println(list);
int choice= scanner.nextInt();

while (choice!=3){
   switch(choice){

   case 1:
    System.out.println(" Option A ");
    System.out.println(list);
    choice = scanner.nextInt();
   break;

   case 2:
   System.out.print (" Enter your name ");
   String name=scanner.nextLine();
   System.out.println(name);
   System.out.println(list);
   choice = scanner.nextInt();
   break;

   default:
   System.out.println(" Invalid choice" );
   System.out.println(list);
   choice = scanner.nextInt();
   break;
}
}

The output when I type "2" :

1- A

2- B

3- quit

Enter your choice

2

Enter your name

1- A

2- B

3- quit

Enter your choice

Snowmap
  • 3
  • 1
  • 7

1 Answers1

1

nextInt() doesnt consumes the whole line so you have to skip that line. So After int choice= scanner.nextInt(); just add scanner.nextLine(); and it will work.

singhakash
  • 7,891
  • 6
  • 31
  • 65