每次运行这个程序时,我得到了错误的结果,我觉得额外的一双眼睛会在早上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() ;
答案 0 :(得分:1)
字符串应与.equals()
方法进行比较,而不是==
。
话虽如此,在您的情况下,您可能需要查看regular expressions,这样您就可以对输入进行 clean 验证。简而言之:
//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") ;
}
答案 1 :(得分:0)
您需要将==
更改为equals
以比较String(和任何其他对象)的值。
你也遇到逻辑问题,因为userGuess != "a" || userGuess != "b"
对所有字符都是正确的,因为如果有a
,那么它不是b
,所以其中一个条件将始终为真。
您可能希望将||
更改为&&
或使用正则表达式等适当的工具,或使用像Character.isLetter
这样的Character类中的方法。