我对此非常陌生,并且正在通过一个教程进行工作,但想用一段时间循环来体验它,以便程序重复,直到“K”为止由用户输入。 不幸的是,当输入不正确的字符时,这似乎读取回车符和换行符。这意味着“错误”被输出三次而不是一次。 有什么办法可以排除这些只读字符吗?在此先感谢Java:如何从System.in.read中排除回车/换行
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**");
}
}
}
你可以尝试使用do-while语句。 – Bubletan