0

I'm making a simple rock, paper, scissors program. For some reason this while loop keeps looping even if the user enters one of the correct terms. Can someone explain why this is happening?

public static String userChoice(){
    String userChoice = "";
    while(userChoice != "rock" && userChoice != "paper" && userChoice != "scissors"){
        userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");

        JOptionPane.showMessageDialog(null, "Invalid input!");
    }

    return userChoice;
}
TheSuds13
  • 327
  • 2
  • 3
  • 8
  • 1
    try using `!(userChoice.equalIgnoreCase("rock"))` instead of `userChoice != "rock"` – Ankur Singhal Jul 28 '15 at 04:25
  • Ahhhh thank you very much. It worked! I never even knew that method existed. It will make it so much easier when comparing strings! – TheSuds13 Jul 28 '15 at 04:29
  • @ankur-singhal one more question kind sir. When the user enters rock, paper, or scissors it still finishes going through the loop. I thought it would break out of the loop as soon as the parameters for the while loop weren't met anymore. Am I going to have to create a conditional statement for the invalid message part? Or is there an easier way – TheSuds13 Jul 28 '15 at 04:33
  • Don't use "==" or "!=" for strings. – user2864740 Jul 28 '15 at 04:34
  • @TheSuds13 it enters `inside` the loop until condition is not met, once condition is met ie users enters `rock, paper, or scissors` it will not go inside loop, and executes statement outside the while loop. i hope it sis clear. – Ankur Singhal Jul 28 '15 at 04:36
  • @ankur-singhal I know, but does it finish going through the loop if the user enters rock, paper, or scissors, or does it break out of the loop immediately when the condition is met? – TheSuds13 Jul 28 '15 at 04:53
  • @TheSuds13 breaks..!!! – Ankur Singhal Jul 28 '15 at 05:07

1 Answers1

-1

you cannot compare String with the standard comparators, you want to use someString.equalsIgnoreCase(someOtherString)

Edit: You can in certain (rare) situations use standard comparators, however this is not one of them.

Epicblood
  • 1,167
  • 2
  • 10
  • 29
  • 1
    cannot compare ? sometimes you can.this is not clear answer – while true Jul 28 '15 at 04:32
  • @whiletrue yes you can but only in very rare situations, and if you are in one of those situations you do not go to stackoverflow looking to see if you can. – Epicblood Jul 28 '15 at 04:33