作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对此非常陌生,正在学习教程,但想用 while 循环来装饰它,以便程序重复直到用户输入“K”。不幸的是,当输入错误的字符时,这似乎会读取回车符和换行符。这意味着“WRONG”会输出三次,而不是一次。有什么方法可以排除这些,以便只读取字符?提前致谢
class Guess{
public static void main(String args[])
throws java.io.IOException {
char ch, answer ='K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = (char) System.in.read(); //read a char from the keyboard
while (ch != answer) {
System.out.println("**WRONG**");
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = (char) System.in.read(); //read a char from the keyboard
if (ch == answer) System.out.println("**Right**");
}
}
}
最佳答案
我建议使用Scanner
并在用户点击返回时读取该行,因为read
将返回视为另一个字符,例如:
char answer ='K';
Scanner scanner = new Scanner(System.in);
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
String ch = scanner.nextLine(); //read a char from the keyboard
while (ch.length() > 0 && ch.charAt(0) != answer) {
System.out.println("**WRONG**");
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = scanner.nextLine();//read a char from the keyboard
}
System.out.println("**Right**");
scanner.close();
关于Java:如何从 System.in.read 中排除回车/换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331757/
我是一名优秀的程序员,十分优秀!