Java:如何从System.in.Read排除运输返回/线馈电



我对此非常陌生,并通过教程进行工作,但想使用一段时间的循环进行构想,以便该程序重复直到用户输入" 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**");
        }
    }
}

我建议使用 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();

这只是陈述顺序。尝试这个

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:");
        }
    }
}

最新更新