-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
56 lines (43 loc) · 2.05 KB
/
NumberGuessingGame.java
File metadata and controls
56 lines (43 loc) · 2.05 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
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int maxAttempts = 5;
int roundsWon = 0;
boolean playAgain;
System.out.println("Welcome to the Number Guessing Game!");
do {
int numberToGuess = random.nextInt(100) + 1; // Generate a random number between 1 and 100
int attempts = 0;
boolean guessedCorrectly = false;
System.out.println("\nI have generated a number between 1 and 100. Can you guess it?");
System.out.println("You have " + maxAttempts + " attempts.");
while (attempts < maxAttempts) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
attempts++;
if (userGuess == numberToGuess) {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
guessedCorrectly = true;
roundsWon++;
break;
} else if (userGuess < numberToGuess) {
System.out.println("Too low. Try again.");
} else {
System.out.println("Too high. Try again.");
}
System.out.println("Attempts left: " + (maxAttempts - attempts));
}
if (!guessedCorrectly) {
System.out.println("Sorry, you've used all your attempts. The correct number was " + numberToGuess + ".");
}
System.out.print("Do you want to play another round? (yes/no): ");
String response = scanner.next().toLowerCase();
playAgain = response.equals("yes");
} while (playAgain);
System.out.println("\nGame over! You won " + roundsWon + " round(s). Thanks for playing!");
scanner.close();
}
}