[英]Java: how to exclude carriage return/ line feed from System.in.read
我对此很陌生,正在研究一个教程,但想通过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
并在用户点击return时读取该行,因为read
会将return视为另一个字符,例如:
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();
这只是陈述令。 尝试这个
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:");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.