dimanche 10 février 2019

How to check if a string entered by a user is a certain letter in Java?

I know this a duplicate question but my question deals more with boolean operators: I'm building a simple rock, paper, scissors game. Each player must enter "R", "P", or "S".

This simple if statement

if (!p1Input.equals("R") || !p1Input.equals("P") || !p1Input.equals("S")) {
    System.out.println("Player one, not a valid input.")
}

should run the print statement if the string is not those three letters. However, even if the string equals one of the letters, it still prints out an invalid input.

Alternatively, I can do

if (p1Input.equals("R") || p1Input.equals("P") || p1Input.equals("S"))

And this works, but I need to incorporate player 2's input to with

if (p1Input.equals("R") || p1Input.equals("P") || p1Input.equals("S") && p2Input.equals("R") || p2Input.equals("P") || p2Input.equals("S"))

but the statement only prints not valid if both the player inputs are not R,S, or P. I'm not sure which operators && or || to use and where. Preferably I want to use a "not equals condition"

Aucun commentaire:

Enregistrer un commentaire