G
G
gleendo2016-11-21 21:56:47
Java
gleendo, 2016-11-21 21:56:47

Why is the text displayed 2 times?

There is such a small code example:

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

        System.out.println("Задумана буква из диапозона A-Z.");

        while (true) {
            System.out.print("Попытайтесь ее угадать: ");

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

            if (ch == answer) {
                System.out.println("** Правильно! **");
                break;
            }
        }
    }
}

Why is the console displaying "Try to guess it: Try to guess it: "??
Why 2 times?
Conclusion: Link to large size
fe93f32e050541a3acced13352cd2e2c.png

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim, 2016-11-21
@z17

In such cases, you need to run the debugger.
And so because you enter 2 characters, not one. Some letter and line break character.

G
gr8web, 2016-11-21
@gr8web

What should be output? :)
I went into the loop, printed out a line, counted the spell.
If the character is not the same, then again output the string and read the character, otherwise if and exit the loop.

A
Anton, 2016-11-21
@MoonMaster

Because that's how the cycle works. When the loop just starts while (true) then the corresponding message is displayed. Then you ask for a symbol. If it's not correct, you print a message, but you don't exit the loop. You just exit the if section.

B
brucebanner, 2016-11-21
@brucebanner

If the if condition is false, the loop is repeated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question