简体   繁体   English

如何检查用户输入的字符串在Java中是否是某个字母?

[英]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". 每个玩家必须输入“ R”,“ P”或“ S”。

This simple if statement 这个简单的if语句

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. 如果字符串不是这三个字母,则应运行print语句。 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 这可行,但是我需要将播放器2的输入与

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 || 但是该语句仅在两个播放器输入都不都是R,S或P时才打印无效。我不确定哪个运算符&&或|| 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 or S, it's invalid". 基本上,当检查输入时,您对程序说:“如果输入与R P S不同,则它无效”。 Well, let's say that the user types "P". 好吧,假设用户键入“ P”。 "P" is different from "R" and different from "S", so your program will consider it to be invalid. “ P”不同于“ R”,也不同于“ S”,因此您的程序将其视为无效。 Instead, trade the "OR" operator ( || ) for the "AND" operator ( && ), like below: 相反,将“ OR”运算符( ||||为“ AND”运算符( && ),如下所示:

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). 现在,您要告诉您的程序,同时输入与“ R” “ P” “ S”不同的输入是无效的(因此不能是任何字母)。

Alternatively, you can try the solution using regex as : 或者,您可以使用regex尝试解决方案:
if(!p1Input.matches("P|R|S")) : this condition will be satisfied when the input is invalid ie other than P, R or S . if(!p1Input.matches("P|R|S")) :当输入无效(即P, R or S if(!p1Input.matches("P|R|S"))时,将满足此条件。 Similarly you can incorporate logic for player2 as well. 同样,您也可以为player2合并逻辑。
Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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