gpt4 book ai didi

Java:如何从 System.in.read 中排除回车/换行

转载 作者:行者123 更新时间:2023-12-02 12:59:19 25 4
gpt4 key购买 nike

我对此非常陌生,正在学习教程,但想用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com