-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomNumber.java
More file actions
28 lines (26 loc) · 1.06 KB
/
RandomNumber.java
File metadata and controls
28 lines (26 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class RandomNumber {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(10) + 1;
try (Scanner input = new Scanner(System.in)) {
while (true) {
try {
System.out.println("Guess a number between 1 and 10:");
int userGuess = input.nextInt();
if (userGuess == numberToGuess) {
System.out.println("Congratulations! You guessed the number.");
break;
} else {
System.out.println("Sorry, wrong guess. Try again.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a number.");
input.next(); // discard the invalid input
}
}
}
}
}