0

For some reason, with this code, tests that I've run shows that the program entirely skips the nextLine request for an input from the user and it registers as blank space for its first iteration. Afterwards it'll go back to the beginning of the while loop and take an input, but no matter what I type in it (whether it's y or Y for yes, N or n for no) it'll go to the else statement. I don't understand what I'm doing wrong, help!

private static boolean promptForPlayAgain(Scanner inScanner) {

    boolean play = true;
    int test = 0;

    while(test == 0)
    {   
        System.out.println("Would you like to play again [Y/N]?:");
        String input = inScanner.nextLine();
        System.out.println(input);

        if (input == "y" || input == "Y")
        {
            test++;
        }
        else if (input == "n" || input == "N")
        {
            play = false;
            test++;
        }
        else
        {
            System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
        }
    }
    return play;
}

2 Answers2

0

For some reason I forgot (I'm sorry), the first line of the input is sometimes empty, add inScanner.nextLine() before you define input to skip that empty line.

brentmaas
  • 1
  • 1
0

With the tips from what you guys said I've edited and ran my code which now works. Thanks a lot guys!

private static boolean promptForPlayAgain(Scanner inScanner) {

    boolean play = true;
    int test = 0;

    while(test == 0)
    {   
        System.out.println("Would you like to play again [Y/N]?:");
        inScanner.nextLine();
        String input = inScanner.nextLine();

        if (input.equals("y") || input.equals("Y") )
        {
            test++;
        }
        else if (input.equals("n") || input.equals("N") )
        {
            play = false;
            test++;
        }
        else
        {
            System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
        }
    }
    return play;
}