I
I
Ilya Podolsky2021-03-17 22:11:53
Java
Ilya Podolsky, 2021-03-17 22:11:53

Why does the do-while loop work weird?

The question is extremely simple.
I want to make sure that the program does not stop until the hidden letter is guessed.
Why does the following code output multiple lines of "Guess the letter from AZ: " instead of just one?

public class HelloWorld {
    public static void main(String[] args)
            throws java.io.IOException {

        char ch;
        do {
            System.out.print("Угадайте букву от A-Z: ");
            ch = (char) System.in.read(); //считываем символ
        } while (ch != 'Q');
    }
}


Program result:
Guess a letter from AZ: f
Guess a letter from AZ: Guess a letter from AZ: Q
<- two lines for some reason The

strange thing is that absolutely similar example works. I would like a detailed analysis.
Second example:

public class HelloWorld {
    public static void main(String[] args)
            throws java.io.IOException {
        char ch, ignore, answer = 'K';

        do {
            System.out.println("Загадана буква от A-Z");
            System.out.print("...попробуйте ее угадать ");

            ch = (char) System.in.read();

            do {
                ignore = (char) System.in.read();
            } while (ignore != '\n');

            if (ch == answer) System.out.println("***right***");
            else {
                System.out.println("Извините, не правильно :(");
                if (ch < answer) System.out.println("Буква ближе к концу алфавита");
                else System.out.println("Буква ближе к началу алфавита");
            }
        } while (answer != ch);
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2021-03-17
@lamerizhottabicha

1. in.read() reads one byte.
2. The f and ENTER you typed remain in the buffer.
3. Data is transferred to the stream when you press ENTER.
Therefore, the first time it reads f, the second time it reads the buffered INPUT.
Use java.util.Scanner which will allow you to read the entire line.
Or, at worst, skip the buffered bytes System.in.skip(System.in.available());

J
Java Developer, 2021-03-19
@Elxanjv_1

Do - performs then checks with while
While - checks then executes

D
Deiwan, 2021-04-06
@Deiwan

If memory serves me right, then (1 code) in do while, the do block is first used, and then while, and since you have derivation in do, therefore, twice

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question