Java do-while loop skipping console input [duplica

2019-02-28 20:38发布

问题:

This question is an exact duplicate of:

  • What's wrong with For Loop? 2 answers
class Noob1 {
    public static void main(String args[]) 
        throws java.io.IOException{

        char ch, answer;
        answer = 'g';

        do {
            System.out.println("Guess from A-L:");
            ch = (char) System.in.read();
                if(ch == answer){
                    System.out.println("Congratz!");
            } else System.out.println("Try again!");
        } while (ch != answer);
    }
}

The output is this:

Guess from A-L:
a
Try again!
Guess from A-L:
Try again!  // this is where intuitively it should ask for input again
Guess from A-L:
Try again!
Guess from A-L:
g           //  input is skipped a few times
Congratz!

I cannot figure out why, I'm reading a book for beginners and everything should've been covered, what am I missing?

Adding the code below at the end of the loop confirms that it is being looped but the input is somehow skipped.

i++;
System.out.println(i);

So I got it working using this:

import java.io.*;

class Noob1 
{
    public static void main(String args[]) throws java.io.IOException
    {
        char ch, answer;
        String tmp;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        answer = 'g';

            do 
            {
                System.out.println("Guess character followed by ENTER:");
                tmp = bufferedReader.readLine();
                ch = tmp.charAt(0); // only first char is considered
                if (ch == answer) 
                    System.out.println("Gratz! the answer was: " + ch + "!");
                else 
                    System.out.println("Nope, try again..");
            } while (ch != answer);
    }
}

Is the formatting still terrible?

回答1:

read only reads a single character, but when answering, you're typing more than one character: You're typing a followed by a newline, because console input doesn't get sent to the stream until you press Enter. That newline sits there in the stream waiting to be read by the next read, which is why it doesn't wait for you to type something again.

You may want to wrap System.in in a BufferedReader and use BufferedReader#readLine and handle the fact you get a string instead of one character, or alternately after getting your character, call read repeatedly until you get the newline. I'd opt for bufferedReader.



回答2:

You are entering 2 characters at once - the character itself and a '\n' new line character. Replace your implementation of reading the character with this :

Scanner s= new Scanner(System.in);
char x = s.next().charAt(0);

charAt makes sure only first character is extracted.