Search code examples
javaconsoleminesweeper

Java equals does not work in the way I'd expect it to work


In my While loop after the first loop it does break out of the While loop but it does not step into my If check, does anyone see what I've done wrong?

    while (!"Y".equals(inputString) && !"N".equals(inputString)) {
        inputString = Helper.InputHelper().toUpperCase();
        if (inputString.equals("N")) {
            System.out.println("Thank you for playing!");
            System.exit(0);
        } else if (inputString.equals("Y")) {
            System.out.println("Starting a new game");
            MineSweeper game;
            game = new MineSweeper();
        }
    }

Everyone is right I'm braindead, changed it to

System.out.println("Would you like to play another game? (Y/N): ");
    String input = "";
    while (!"Y".equals(input) && !"N".equals(input)) {
        input = Helper.InputHelper().toUpperCase();
        if (input.equals("N")) {
            System.out.println("Thank you for playing!");
            System.exit(0);
        } else if (input.equals("Y")) {
            System.out.println("Starting a new game");
            MineSweeper game;
            game = new MineSweeper();
        }
    }

and works flawless thank you.


Solution

  • i bet this is what you want.

    Scanner input = new Scanner(System.in);
        while (true) {        
            String answer = input.next().toUpperCase();
            if (answer.equals("N")) {
                System.out.println("Thank you for playing!");
                // don't forget to close you scanner
                input.close();
                System.exit(0);
                break;
            } else if (answer.equals("Y")) {
                System.out.println("Starting a new game");
                MineSweeper game;
                game = new MineSweeper();
                input.close();
                break;
            } else {
                // if you don't get appropriate answer from users then warn them about it
                System.out.println("Please type either Y or N");
            }
        }
    

    either way, when you hit the condition, you should break, otherwise there is no stooping that loop.