我对此非常陌生并且正在完成一个教程,但是希望用一个while循环来使用它,以便程序重复直到用户输入“K”。 不幸的是,当输入错误的字符时,这似乎会读取回车符和换行符。这意味着“错误”输出三次而不是一次。 有没有办法排除这些,以便只读取字符?提前致谢
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**");
}
}
}
答案 0 :(得分:1)
我建议使用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();
答案 1 :(得分:0)
这只是法令的命令。 试试这个
public 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) {
ch = (char) System.in.read(); //read a char from the keyboard
if (ch == answer) {
System.out.println("**Right**");
break;
}else{
System.out.println("**WRONG**");
}
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
}
}
}