S
S
Sergey2017-03-26 14:54:15
Java
Sergey, 2017-03-26 14:54:15

Why does do-while work like this?

Good day!
Actually, I began to learn Java, simultaneously trying the listings from the examples in the book. Reached do-while. And then I got stuck:

char i;
        boolean a;
        do {
            System.out.println("Введите значение от 1 до 3 ");
            i = (char) System.in.read();
            a = (boolean) (i<'1' | i>'3');
            System.out.println(a);
        }
        while (a);
        System.out.println(i);

or
char i;
        do {
            System.out.println("Введите значение от 1 до 3 ");
            i = (char) System.in.read();
        }
        while (i<'1' | i>'3');
        System.out.println(i);

We enter i from 1 to 3 - everything is ok. Enter i greater than 3 or less than 1 - the line "Enter a value from 1 to 3" is displayed twice. By changing the conditions, it becomes clear that the matter is in it - we leave only, for example, i> 3 - "Enter a value from 1 to 3" is repeated 1 time.
Hence the question: why the check while (i<'1' | i>'3'); performed in 2 passes, not 1? What is the order of code execution in this case? And how for my example to make a conclusion of a condition only 1 time?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
NameOf Var, 2017-03-26
@x__miller_x

It outputs twice because after entering the number you press the "Enter" key and the stream is passed the character '\n', which is processed a second time. So, for example, if you enter the number 4, then Java will process the string "4\n". You can add a check for comparison with the character '\n'.

K
Kirill Romanov, 2017-03-26
@Djaler

||

B
barker, 2017-03-26
@barker

Well, a line feed after the first digit, no?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question