This repository was archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
47 lines (37 loc) · 1.71 KB
/
NumberGuessingGame.java
File metadata and controls
47 lines (37 loc) · 1.71 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
44
45
46
47
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
// Create a Random object to generate random numbers
Random random = new Random();
// Generate a random number between 1 and 100
int targetNumber = random.nextInt(100) + 1;
// Maximum number of attempts
int maxAttempts = 10;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I have generated a random number between 1 and 100.");
System.out.println("You have " + maxAttempts + " attempts to guess it.");
// Variable to track the number of attempts used
int attempts = 0;
while (attempts < maxAttempts) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
attempts++;
if (guess == targetNumber) {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
break;
} else if (guess < targetNumber) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
if (attempts == maxAttempts) {
System.out.println("Sorry, you've used all " + maxAttempts + " attempts. The correct number was " + targetNumber + ".");
}
}
// Close the scanner
scanner.close();
}
}