0
if (sum < 6) {
    System.out.println("You win");
    System.out.println();
    // Does the user want to retry?
    System.out.print("Would you like to retry?(Y or N) : ");
    String retry = input.nextLine();

    while (true) {
        // If they say y or Y, roll again
        if (("y".equals(retry)) || ("Y".equals(retry))) {
            roll();
        // Check for anything other than y and Y
        } else if (("n".equals(retry)) || ("N".equals(retry))) {
            System.out.println("Closing");
            break;
        } else if (!("y".equals(retry)) || !("Y".equals(retry))) {
            System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
            retry = input.nextLine();
            System.out.println();

        }
    }
} else if (sum > 6) {
    System.out.println("You lose");
    System.out.println();
    System.out.print("Would you like to retry?(Y or N) : ");
    String retry = input.nextLine();
    while (true) {
        if (("y".equals(retry)) || ("Y".equals(retry))) {
            roll();
        } else if (("n".equals(retry)) || ("N".equals(retry))) {
            System.out.println("Closing");
            break;
        } else if (!("y".equals(retry)) || !("Y".equals(retry))) {
            System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
            retry = input.nextLine();
            System.out.println();
        }
    }
}

I'm trying to make a dice game where the game will keep rolling the dices when the user inputs "y" or "Y". I also want it to stop the game and say "Closing" when the user inputs "n" or "N".

The issue is, when the user inputs "n" or "N", it will print out "Closing" but the loop doesn't stop and the game will roll the dices again. How to I make my while() loop stop when the user inputs "n" or "N"?

Here's the output when the user chooses to stop the game ("n" or "N") : Would

you like to retry?(Y or N) : n
Closing
Rolling...
You rolled : 1 & 4
Sum = 5
You win

I'm sorry for such basic question, I am new to programming.

luk2302
  • 55,258
  • 23
  • 97
  • 137
Crypto
  • 60
  • 1
  • 10
  • Quick edit : if the user inputs "n" or "N" on the first "retry?", the game will close. But if he inputs "y" or "Y" and then chooses to stop the game, the loop will keep going. – Crypto May 14 '17 at 21:37
  • 1
    How is supposed to be a duplicate @JarrodRoberson ? Just because he uses `Scanner` it is not a duplicate, he had a logic error, nothing really related to scanning from System.in - the misplaced line just happened to make use of a scanner, but the issue itself is completely unrelated to Scanners. – luk2302 May 15 '17 at 08:23

1 Answers1

5

Move the line String retry = input.nextLine(); into the while loop (in both if branches). Currently you read in one input and then compare that non-changing input over and over again.

luk2302
  • 55,258
  • 23
  • 97
  • 137