我知道你可以将 Java 中的字符与普通运算符进行比较,例如anysinglechar == y
。但是,我对这个特定的代码有一个问题:
do{
System.out.print("Would you like to do this again? Y/N\n");
looper = inputter.getChar();
System.out.print(looper);
if(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n')
System.out.print("No valid input. Please try again.\n");
}while(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n');
问题不应该出在其他方法 inputter.getChar() 上,但无论如何我都会转储它:
private static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
public static char getChar() throws IOException{
int buf= read.read();
char chr = (char) buf;
while(!Character.isLetter(chr)){
buf= read.read();
chr = (char) buf;
}
return chr;
}
我得到的输出如下:
Would you like to do this again? Y/N
N
NNo valid input. Please try again.
Would you like to do this again? Y/N
n
nNo valid input. Please try again.
Would you like to do this again? Y/N
正如你所看到的,我输入的字符是n
。然后它会被正确打印出来(因此要被看到两次)。然而,这种比较似乎并不成立。
我确信我忽略了一些显而易见的事情。
你的逻辑不正确。它总是true
that looper
isn't 'Y'
or不是'y'
or这不是...
您需要“and”的逻辑运算符:&&
if(looper != 'Y' && looper != 'y' && looper != 'N' && looper != 'n')
以及你的类似变化while
健康)状况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)