[英]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.