0

I am making a rock paper scissors program. I want the user of the program to enter either rock, paper, or scissors (hence the imported scanner) and I want the computer to choose a random number (I will import a java.util.Random) that corresponds to another rock, paper, or scissor.

So I am trying to make the program RECOGNIZE a word as something significant. That is to say, if the user inputs "rock" in the scanner, the computer will do some output. In the below code, I tried to get the computer to output "yes" if the user inputs "rock". To do this, I set a variable called "player" to be the inputted text, and a String rock to be the phrase "rock". I then said that if player=rock(="rock"), then we will get "yes".

There were no errors in the program. But when I inputted "rock" into the scanner, the program did nothing. What did I do wrong and how can I correct it?

import java.util.Scanner;

public class Refined {

    public static void main(String[] args){
        Scanner abc = new Scanner(System.in);
        String rock = "rock";

        String player;
        System.out.println("Rock, Paper, or Scissors?");
        player = abc.next();
        if(player == rock){
            System.out.println("yes");

        }
    }

3 Answers3

1

Use player.equals(rock) or player.equalsIgnoreCase(rock) to compare contents of both variables

If we apply == to compare two string objects it compares the references of both the objects so in your case references are difference that is why it is returning false and System.out.println("yes"); is not being printed.

Use String.equals() or String.equalsIgnoreCase() method to compare contents of the string.

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
0

You want player.equals(rock) in the if condition.

Putting player == rock compares the String objects (basically whether the references in memory point at the same spot), not the value actually stored in the String objects.

0

player and rock are String objects. In Java we dont have String as a datatype, like int, float, etc. So to compare two objects we must use .equals() [ which comes from the Object class ]

codingsplash
  • 4,785
  • 12
  • 51
  • 90