Java char比较似乎不起作用

时间:2013-05-09 16:37:20

标签: java comparison char conditional-statements

我知道您可以将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。然后将其正确打印出来(因此可以看到两次)。但是,这种比较似乎并不成真。

我确定我忽略了一些显而易见的事情。

1 个答案:

答案 0 :(得分:4)

你的逻辑错误。始终为true looper不是'Y' 它不是'y' 它不是'{1}} t ...

您想要“和”的逻辑运算符:&&

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

以及while条件中的类似更改。