Why are my if-else statements not printing what they're supposed to?

Mica

New Member
#1
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".
Mã:
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?
 

Admin

Administrator
Thành viên BQT
#2
== tests for reference equality and

.equals() tests for value equality.

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

Mã:
if (userAnswer.equals(compAnswer)) {}
So your code will like this:
Mã:
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!");
        }
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top