A
A
artem2020-09-18 18:51:45
Java
artem, 2020-09-18 18:51:45

Explain why it works this way?

public class javart {
    public static void main(String[]args)
    throws java.io.IOException {
            char ch, ignore, answer = 'S';
            do {
                System.out.println("Зaдyмaнa буква из диапазона A-Z.");
                System.out.print("Пoпытaйтecь ее угадать: ");
                // Получить символ с клавиатуры
                ch = (char) System.in.read();
                // Отбросить все остальные символы во входном буфере
                do {
                    ignore = (char) System.in.read();
                } while(ignore != '\n'); 
            if(ch == answer) System.out.println("** Правильно! **");
                else {
                System.out.print(" ... Извинитe, нужная буква находится ");
                if(ch < answer)
                System.out.println("ближe к концу алфавита");
                else System.out.println("ближe к началу алфавита");
                System.out.println("Пoвтopитe попытку!\n");}
                
            }while(answer != ch); 
            }

    }


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

I know that it skips writing to the buffer and thus avoids re-outputting the conditions, but why is that?
Why does he skip them, and is not "meaningless"? I understand this logic like this, we take the value of the keyboard input until the line breaks, then we continue to execute the main loop. And in theory this cycle is simply "useless" Please explain.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2020-09-18
@arteqrt

It looks like this was done to remove possible duplicates. Press the keyboard button and hold, you will see that not one letter will be printed, but a series. And this whole series will fly away to System.in.
So it turns out that you either need to skip everything that comes after the first letter, or there will be several messages in a row on the screen that the attempt to guess failed. Those. Here, as it were, the road is being cleared for the next attempt.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question