-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
43 lines (37 loc) · 1.53 KB
/
NumberGuessingGame.java
File metadata and controls
43 lines (37 loc) · 1.53 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int lower = 1;
int upper = 100;
int maxAttempts = 7;
Random rand = new Random();
int secretNumber = rand.nextInt(upper - lower + 1) + lower;
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between " + lower + " and " + upper + ".");
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
System.out.print("Attempt " + attempt + "/" + maxAttempts + ": Take a guess: ");
int guess;
if (scanner.hasNextInt()) {
guess = scanner.nextInt();
} else {
System.out.println("Please enter a valid integer.");
scanner.next();
attempt--;
continue;
}
if (guess < secretNumber) {
System.out.println("Too low!");
} else if (guess > secretNumber) {
System.out.println("Too high!");
} else {
System.out.println("Congratulations! You guessed the number in " + attempt + " attempts.");
scanner.close();
return;
}
}
System.out.println("Sorry, you've run out of attempts. The number was " + secretNumber + ".");
scanner.close();
}
}