Brandy C Zoch
Brandy C Zoch

Reputation: 65

Program is misreading my input

So. I'm doing a tutorial on java and playing with making a D&D character sheet saver. The problem I'm having is not a serious one but after I've commanded it to load, it does the message as expected but then when I input 'new' and hit enter it waits until I hit enter again and then it does my else code instead of my if for "new". I end up having to type it again.

do {
        if (command.equalsIgnoreCase("new")) {
            System.out.println("Let's create a character!\n");

then a bunch of other code that doesn't matter and then:

    // LOAD CHARACTER
        else if (command.equalsIgnoreCase("load")) {
            // placeholder for load char.
            System.out
                    .println("This is where we will load a character in the     future.  For now it is empty, please select new.");
            command = text.nextLine();
            // EXIT CODE
        } else if (command.equalsIgnoreCase("exit")) {
            System.exit(0);

            // Invalid Response
        } else
            System.out.println("Invalid response. Please try again. ");
        command = text.nextLine();
    } while (!command.equalsIgnoreCase("exit"));

and here's how it comes out:

Please say 'New' for a new character or 'Load' to load a previously saved character...
Load
This is where we will load a character in the future. For now it is empty, please select new.
new

Invalid response. Please try again.
new
Let's create a character!

What is this character's name?

Upvotes: 2

Views: 80

Answers (2)

Thomas
Thomas

Reputation: 5094

You have command = text.nextLine(); in both your 'load' if section and at the end of the loop. The first input is taken in the if block, then the blank line is read and is what gets compared in your if/else stream for the next round.

Putting the input reading outside the if-else chain is the preferable way to do it, since you don't have duplicate code in each else block.

do {
    if (command.equalsIgnoreCase("new")) {/*do new stuff*/} 
    else if (command.equalsIgnoreCase("load")) {/*do load stuff*/}
    else if (command.equalsIgnoreCase("exit")) {/*do exit stuff*/}
    else {/*do default/bad input stuff*/}

    //This line runs every loop iteration(unless one of your if blocks calls break or exit
    command = text.nextLine();
} while (!command.equalsIgnoreCase("exit"));

Upvotes: 4

Jacob is on Codidact
Jacob is on Codidact

Reputation: 3750

After printing This is where we will load ..., you read input twice before checking the input again. Once immediately after the message, and again at the end of the loop.

Upvotes: 2

Related Questions