简体   繁体   中英

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"

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 S, it's invalid". S不同,则它无效”。 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).

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 ie other than P, R or S . Similarly you can incorporate logic for player2 as well.
Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM