Dean
Dean

Reputation: 8978

String not being printed when Inputting using scanner class

I have the following code fragment but when I execute it is not printing out the value of the die.

Here is the source code:

System.out.println("Player 1s Go.\nEnter R to Roll and H to Hold");
input = scanner.next();
while (input.equals("R")) {
    input = scanner.next();
    die.throwDie();
    System.out.println("Value on Die: " + die.getFaceValue());
    if (rolledOne()) {
        player1Rolled.clear();
        System.out.println("Player 1 scored 0, End of turn");
        holdPlayer1 = true;
        holdPlayer2 = false;
        break;
    } else {
        player1Rolled.add(die.getFaceValue());
    }
}

getFaceValue() is a accessor method for the die class which returns the value of the die. throwDie() is a mutator method which changes the value and simulates the rolling of a die.

The output I get is the following:

Player 1s Go.
Enter R to Roll and H to Hold
*R
R*
Value on Die: 5
*R*
Value on Die: 5
*R*

Notice that I have to tell it to roll twice, it is rolling twice but only printing out of the value of the second roll.

Upvotes: 0

Views: 89

Answers (1)

GenericJon
GenericJon

Reputation: 8986

You call scanner.next() twice. Once outside the loop and once inside. If the first input is "R" then it enters the while loop and immediately waits for a new input.

Moving input = scanner.next(); to the end of the loop rather than the start I think should give you the behaviour you're looking for.

Upvotes: 1

Related Questions