gpt4 book ai didi

JAVA if 语句逻辑或语法错误?

转载 作者:行者123 更新时间:2023-12-01 13:08:13 25 4
gpt4 key购买 nike

每次运行这个程序时,我都会得到错误的结果,我觉得在凌晨 4 点多一双眼睛会有所帮助。有人可以帮我找到我的大括号或括号的位置吗,因为我一辈子都找不到它。

System.out.println("Please enter your guess") ;
userGuess = kbd.next() ;
if( userGuess != "a" || userGuess != "b" || userGuess != "c" ||
userGuess != "d" || userGuess != "e" || userGuess != "f" || userGuess != "g" ||
userGuess != "h" || userGuess != "i" || userGuess != "j" || userGuess != "k" ||
userGuess != "l" || userGuess != "m" || userGuess != "n" || userGuess != "o" ||
userGuess != "p" || userGuess != "q" || userGuess != "r" || userGuess != "s" ||
userGuess != "t" || userGuess != "u" || userGuess != "v" || userGuess != "w" ||
userGuess != "x" || userGuess != "y" || userGuess != "z" || userGuess!= "A" ||
userGuess != "B" || userGuess != "C" || userGuess != "D" || userGuess != "E" ||
userGuess != "F" || userGuess != "G" ||userGuess != "H" || userGuess != "I" ||
userGuess != "J" || userGuess != "K" ||userGuess != "L" || userGuess != "M" ||
userGuess != "N" || userGuess != "O" || userGuess != "P" || userGuess != "Q" ||
userGuess != "R" || userGuess != "S" || userGuess != "T" || userGuess != "U" ||
userGuess != "V" || userGuess != "W" || userGuess != "X" || userGuess != "Y" ||
userGuess != "Z" ) {
System.out.println("Invalid character, please enter your guess") ;
}userGuess = kbd.next() ;

最佳答案

字符串应该与 .equals() 方法进行比较,而不是 ==

话虽如此,在您的情况下,您可能想看看 regular expressions ,这将允许您对输入进行干净验证。简而言之:

//This code is untested, but it should guide you to what you need to do
Pattern userInput = Pattern.compile("^[A-Za-z]$"); //A-Z will match all the characters ranging from A to Z. a-z will do the same but it will check the lower case range. Alternatively, you could use ^[a-z]/i$ to make your regular expression case insensitive.
Scanner kbd = new Scanner(System.in);
String input = kbd.next();
Matcher matcher = userInput.matcher(input);
if(!matcher.matches())
{
System.out.println("Invalid character, please enter your guess") ;
}

关于JAVA if 语句逻辑或语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com