user9440272
user9440272

Reputation:

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"

Upvotes: 0

Views: 1295

Answers (2)

Nisarg Patil
Nisarg Patil

Reputation: 1639

Alternatively, you can try the solution using regex as :
if(!p1Input.matches("P|R|S")) : this condition will be satisfied when the input is invalid i.e. other than P, R or S. Similarly you can incorporate logic for player2 as well.
Hope this helps.

Upvotes: 0

Talendar
Talendar

Reputation: 2087

It's a problem with your boolean logic. Basically, when checking the input, you are saying to your program: "if the input is different from R or P or S, it's invalid". Well, let's say that the user types "P". "P" is different from "R" and different from "S", so your program will consider it to be invalid. Instead, trade the "OR" operator (||) for the "AND" operator (&&), like below:

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

Now, you are telling your program that an input is invalid when it is different, at the same time, from "R" and "P" and "S" (so it can't be any of those letters).

Upvotes: 2

Related Questions