0

I am creating a program that simulates Rock, Paper, Scissors, and I need the user to input either "Rock","Paper", or "Scissors". My Code is:

    Scanner input = new Scanner(System.in);
    String userIn = null;

    while ((userIn != "Rock") || (userIn != "Paper") || (userIn != "Scissors")) {
        System.out.println("Please Type either: Rock, Paper or Scissors");
        userIn = input.next(); 
    }

I created a scanner for the input and set the initial input to null. When the program runs, since the input is not either "Rock","Paper", or "Scissors", it will prompt the user to enter one of those three, the problem is even when I enter "Rock","Paper", or "Scissors" correctly, it still reprompts me to "Please Type either: Rock, Paper or Scissors".

what am I doing wrong?

Jotaro
  • 707
  • 2
  • 6
  • 7

4 Answers4

0

For string comparisons use userIn.equals("yourString") function rather than != comparisons.

Ajinkya Patil
  • 741
  • 1
  • 6
  • 17
0

You should try using .equals() or better .equalsIgnoreCase() if you are not bothered about the case of the input string. That might help.

saurabh kedia
  • 321
  • 2
  • 11
0

equal or equalsIgnoreCase uses the content of object to make compare,but != do the comparison with the reference address so the code should be

while ((userIn.equalsIgnoreCase("Rocker")) || (userIn.equalsIgnoreCase("Paper") || (userIn.equalsIgnoreCase("Scissors"))
Javy
  • 944
  • 5
  • 9
0

Update your program like this,

Scanner input = new Scanner(System.in);
    String userIn = "";

    while (!(userIn.equals("Rock") || userIn.equals("Paper")|| userIn.equals("Scissors"))) {
        System.out.println("Please Type either: Rock, Paper or Scissors");
        userIn = input.next(); 
    }

firstly, if you are doing

String userIn = null; //instead  String userIn = " ";

we can't check

userIn.equals("Rock"); // i.e. null.equals("Rock");

compiler will through a null pointer exception. So, edit your program as above and will work properly.

Pratik Rawlekar
  • 327
  • 4
  • 14