user919860
user919860

Reputation: 3175

Why such weird behavior from my switch statement?

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.

Upvotes: 1

Views: 441

Answers (2)

Jomoos
Jomoos

Reputation: 13083

Assuming that keyboard is an object of java.util.Scanner, the problem lies in the following.

Firstly, you read a byte using nextByte(), thus only the byte value is taken as input. The remaining values, here in your case the newline character is remaining in the input stream. It is read by the keyboard.nextLine() as input and returned. So an empty string is returned by that line. So, you might want to put an extra nextLine() call to discard that new line as follows:

System.out.print("Input the layout type: ");
keyboard.nextLine();
layoutType = keyboard.nextLine();
System.out.print("Input the layout name: ");
layoutName = keyboard.nextLine();

Upvotes: 1

Tudor
Tudor

Reputation: 62469

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 dummy readLine() after readByte() to solve this:

choice = keyboard.nextByte();
keyboard.readLine(); // dummy readline

Upvotes: 2

Related Questions