我知道你可以將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