2013-05-09 75 views
0

我知道你可以將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。然後將其正確打印出來(因此可以看到兩次)。但是,這種比較似乎並不真實。

我確定我忽略了一些明顯的東西。

+0

你試過嗎(a.equals(b))? – cgalvao1993 2013-05-09 16:39:02

+1

@CássioGalvão'(a.equals(b))'如果它的字符串能正常工作。但使用字符「==」。 – Smit 2013-05-09 16:40:40

+1

感謝您的清理,@Leigh。 – hellerve 2013-05-09 16:47:26

回答

3

您的邏輯錯誤。它始終是truelooper不是'Y'它不是'y'它不是...

你想的邏輯運算符 「和」:&&

if(looper != 'Y' && looper != 'y' && looper != 'N' && looper != 'n') 

和您的while條件中的類似更改。

+0

哦,該死的。我知道這是明顯的。對不起,這個愚蠢的問題。 – hellerve 2013-05-09 16:46:57