A while loop that stops on a condition or at the end of the input: replay a number-guessing game.
What to build
A program that answers each guess and reports how the game ended.
Requirements
- Read the secret number, then guesses one at a time.
- For each wrong guess print
G is too loworG is too high. For the right one printG is right after N guessesand stop reading. - If the input ends first, print
gave up after N guesses.
Input
The secret, then guesses, separated by spaces or new lines.
Output
One line per guess read, plus possibly the gave-up line.
Constraints
All numbers are between 1 and 100; at most 50 guesses.
Example
Input:
42
50 25 40 42
Output:
50 is too high
25 is too low
40 is too low
42 is right after 4 guesses
Why it works
The loop runs while there is input, and break leaves it as soon as the guess is right, so later guesses are never read; a counter kept outside the loop knows how many there were.
Examples
Example 1 · Input
42 50 25 40 42
Expected output
50 is too high 25 is too low 40 is too low 42 is right after 4 guesses
Example 2 · Input
7 1 2
Expected output
1 is too low 2 is too low gave up after 2 guesses
Hints
Hint 1
Read guesses with while (in.hasNextInt()) and stop with break when one is right.
Hint 2
Count every guess, the right one included.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int secret = in.nextInt();
int count = 0;
boolean found = false;
while (in.hasNextInt()) {
int g = in.nextInt();
count++;
if (g < secret) System.out.println(g + " is too low");
else if (g > secret) System.out.println(g + " is too high");
else {
System.out.println(g + " is right after " + count + " guesses");
found = true;
break;
}
}
if (!found) System.out.println("gave up after " + count + " guesses");
}
}