我知道你可以将Java中的字符与正常运算符进行比较,例如anysinglechar == y
。但是,我有这个特殊的代码有问题:Java char比较似乎不起作用
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
。然后将其正确打印出来(因此可以看到两次)。但是,这种比较似乎并不真实。
我确定我忽略了一些明显的东西。
你试过吗(a.equals(b))? – cgalvao1993 2013-05-09 16:39:02
@CássioGalvão'(a.equals(b))'如果它的字符串能正常工作。但使用字符“==”。 – Smit 2013-05-09 16:40:40
感谢您的清理,@Leigh。 – hellerve 2013-05-09 16:47:26