Take the following code written in Java:
choice = keyboard.nextByte();
switch (choice)
{
case (byte) 4:
System.out.print("Input the layout type: ");
layoutType = keyboard.nextLine();
System.out.print("Input the layout name: ");
layoutName = keyboard.nextLine();
break;
default:
break;
}
When I run the program, I get the following:
Input the layout type: Input the layout name:
I get prompted for both inputs all at once! Why is that? Shouldn’t the program stop at where it says “keyboard.nextLine()“? It does that outside of the switch statement but not while inside of it. Why does prompting the user for input inside of the switch statement cause this weird behavior?
===================================
UPDATE:
Yes, that’s right. keyboard is an instance of the java.util.Scanner class.
It is because you are inputting a newline in order to read the byte, and the newline is somehow considered input for the subsequent call to
readLine(). Add a dummyreadLine()afterreadByte()to solve this: