0
public static void getSolve(Scanner s) {
    boolean validInput = false;
    while(validInput == false) {
        System.out.println("Would you like to try to solve the word? (yes or no)");
        String input = s.nextLine();
        if(input == "yes" || input == "Yes") {
            validInput = true;
            System.out.println("Enter your full guess: ");
            String guess = s.nextLine();
            if (guess == secretWord) {
                System.out.println("You guessed the word!");
                displayString = secretWord;
            }
            else {
                System.out.println("Sorry, that is not the word");
                NUM_LIVES --;
            }
        }
        else if (input == "no" || input == "No") {
            validInput = true;
        }
        else {
            System.out.println("Sorry, that is not a valid input");
        }
    }
}

This is the code that I am using for a solve method for a java project for my class in which I am coding a hangman game. I am trying to add a feature that asks the user if they would like to try to solve the word and then checks to see if they got that guess correct. Right now what is happening is that no matter what the user puts in, even if it is "yes" or "no", the program thinks that it is an invalid input and asks the question again, putting the code into an infinite loop. I'm not quite sure how to fix this and I'm not sure what I am doing wrong. Any help is greatly appreciated!

  • 5
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Charlie Armstrong Jan 07 '21 at 22:40

2 Answers2

1

Looks good to me except this one:

input == "yes" || input == "Yes"

should be

"yes".equalsIgnoreCase(input)

And others:

guess == secretWord -> guess.equals(secretWord)
input == "no" || input == "No" -> "no".equalsIgnoreCase(input)
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

You need to compare strings using .equals in java.

if(input.equals("yes") || input.equals("Yes"))

You can also use .equalsIgnoreCase() so you don't have to write all forms of the word yes.

.equals() is used to compare objects.

Devon
  • 160
  • 1
  • 12