0

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

我确定我忽略了一些明显的东西。

4

2 回答 2

4

你的逻辑不正确。总是truelooper不是'Y' 不是'y' 不是...

您需要“and”的逻辑运算符:&&

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

和你的情况类似的变化while

于 2013-05-09T16:39:42.810 回答
0

||与其将逻辑运算符从to修复,不如&&让代码更清晰:

private static final Set<Character> YES_OR_NO = Set.of('Y', 'y', 'N', 'n');

do { 
    System.out.print("Would you like to do this again? Y/N\n");
    looper = inputter.getChar();
    System.out.print(looper);
    if (!YES_OR_NO.contains(looper))
        System.out.print("No valid input. Please try again.\n");
} while(!YES_OR_NO.contains(looper));
于 2022-01-30T01:41:20.147 回答