Answer the question
In order to leave comments, you need to log in
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');
}
}
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
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());
Do - performs then checks with while
While - checks then executes
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question