0

I am doing a school coding project, in which (using Dr. Java) I code a game of rock, paper, scissors. My game asks the user for their throw, while randomly generating the computer's throw.

The code below represents my (incomplete) method for determining the winner of the game. It’s supposed to first check if the two throws are the same, then, if they are not, compare the two throws to see who won. The final else-statement is a backup, in case the user inputs an answer other that rock, paper, or scissors.

Currently, the string compAnswer is hardcoded to "rock".

    if (userAnswer == compAnswer)
{  
  System.out.println("Huh. A tie. That was... disappointing.");
  win = 2;
} else if (compAnswer == "rock"){
 { if (userAnswer == "paper") {
    System.out.println("Curses! I threw rock and lost!");
    win = 0;
  } else if (userAnswer == "scissors") {
    System.out.println("Hah! I threw rock and crushed your scissors!");
    win = 1;
  }}
} else {
  System.out.println("...You cheater! That's not a legal throw! Off to the fire and brimstone with you!");
} 

However, when I run my program, nothing gets printed- not when userAnswer gets "paper" or "scissors", or even when the answer is bogus. I’m at a loss here- why are my print statements not being triggered?

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Check out [this question](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) to see how to compare strings in Java. – dave Oct 11 '18 at 02:33

1 Answers1

0

== tests for reference equality and

.equals() tests for value equality.

So, do compare string with equals() method as:

if (userAnswer.equals(compAnswer)) {}

So your code will like this:

if (userAnswer.equals(compAnswer)) {
            System.out.println("Huh. A tie. That was... disappointing.");
            win = 2;
        } else if ("rock".equals(compAnswer)) {
            {
                if ("paper".equals(userAnswer)) {
                    System.out.println("Curses! I threw rock and lost!");
                    win = 0;
                } else if ("scissors".equals(userAnswer)) {
                    System.out.println("Hah! I threw rock and crushed your scissors!");
                    win = 1;
                }
            }
        } else {
            System.out.println("...You cheater! That's not a legal throw! Off to the fire and brimstone with you!");
        }
Yogen Rai
  • 2,961
  • 3
  • 25
  • 37