-3

I wrote a function to receive user input. Can't get the correct answer back. Always Failure. I am losing my mind right now.

public String getChoice() {
    Scanner SC = new Scanner(System.in); 
    System.out.print("Ready to play? (Y/N) ");
    String playChoice = SC.next();    // Input Y or N
    playChoice = playChoice.replace("\n", "");
    System.out.println("Input length is: " + playChoice.length());
    System.out.println(playChoice);
    if (playChoice == "N") {
        SC.close();
        return "Success N";
    }
    else if (playChoice == "Y") {
        SC.close();
        return "Success Y";
    }
    SC.close();
    return "Failure"; // Always this one works
}
roksui
  • 109
  • 1
  • 8
Edmunds Beks
  • 23
  • 1
  • 7

2 Answers2

2

Try this:

 public String getChoice() {
        Scanner SC = new Scanner(System.in);
        System.out.print("Ready to play? (Y/N) ");
        String playChoice = SC.next();    // Input Y or N
        playChoice = playChoice.replace("\n", "");
        if (playChoice.equals("N")) { // Replace operator '==' with 'equals()' method.
            SC.close();
            return "Success N";
        } else if (playChoice.equals("Y")) { // Same here.
            SC.close();
            return "Success Y";
        }
        SC.close();
        return "Failure"; // Always this one works
    }

The reason why your code is not working as intended, is that the == operator compares whether the 2 compared object references are pointing to the same object. This obviously is not the case in your if-statements, and therefore those expressions will always evaluate to false.

the equals() method on the other hand actually compares the content of the given objects , thus delivering the desired result.

Bialomazur
  • 1,122
  • 2
  • 7
  • 18
0

@Bialomazur gave an explanation already and here is a bit cleaner code and tips.

Actually, closing Scanner is not a good practice, but if you decided to, you can close it before your ifs just in one place, since you are not using scanner anymore. Also, switch looks better here

public String getChoice() {
    Scanner SC = new Scanner(System.in);
    System.out.print("Ready to play? (Y/N) ");
    String playChoice = SC.next();    // Input Y or N
    playChoice = playChoice.replace("\n", "");
    System.out.println("Input length is: " + playChoice.length());
    System.out.println(playChoice);
    SC.close();
    switch (playChoice) {
        case "Y":
            return "Success Y";
        case "N":
            return "Success N";
        default:
            return "Failure";
    }
}
eternal
  • 339
  • 2
  • 15