简体   繁体   中英

Java: how to exclude carriage return/ line feed from System.in.read

I am very new to this and working through a tutorial but wanted to fancy it up with a while loop so that the program repeats until "K" is entered by the user. Unfortunately, this seems to read the carriage return and line feed when the incorrect char is entered. This means that " WRONG " is output three times instead of once. Is there any way to exclude these so that only the Character is read? Thanks in advance

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**");

        }

    }
}

I would recommend using Scanner and read the line when user hits return as read considers return as another character, eg:

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();

It's just the statments order. Try this

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

        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM