Java char comparison does not seem to work(Java字符比较似乎不起作用)
本文介绍了Java字符比较似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道您可以将Java中的字符与普通操作符进行比较,例如anysinglechar == y。但是,我对此特定代码有一个问题:
do{
System.out.print("Would you like to do this again? Y/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.
");
}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。然后它被正确地打印出来(因此它将被看到两次)。然而,这种比较似乎并不成立。
我确信我忽略了一些明显的东西。
推荐答案
您的逻辑不正确。它总是true不是'Y'或它不是'y'或它不是.
您需要"and"的逻辑运算符:&&
if(looper != 'Y' && looper != 'y' && looper != 'N' && looper != 'n')
和您的while条件中的类似更改。
这篇关于Java字符比较似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:Java字符比较似乎不起作用
基础教程推荐
猜你喜欢
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
