-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGame.java
More file actions
52 lines (42 loc) · 1.94 KB
/
NumberGame.java
File metadata and controls
52 lines (42 loc) · 1.94 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
import java.util.Random;
import java.util.Scanner;
public class NumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int roundsWon = 0;
boolean playAgain;
do {
int numberToGuess = random.nextInt(100) + 1; // Random number between 1 and 100
int attemptsLeft = 10;
boolean guessedCorrectly = false;
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 10 attempts to guess it!");
while (attemptsLeft > 0 && !guessedCorrectly) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
if (userGuess == numberToGuess) {
guessedCorrectly = true;
System.out.println("Congratulations! You guessed the correct number!");
} else if (userGuess < numberToGuess) {
attemptsLeft--;
System.out.println("Too low! Try again. You have " + attemptsLeft + " attempts left.");
} else {
attemptsLeft--;
System.out.println("Too high! Try again. You have " + attemptsLeft + " attempts left.");
}
}
if (guessedCorrectly) {
roundsWon++;
} else {
System.out.println("Sorry, you're out of attempts! The correct number was " + numberToGuess + ".");
}
System.out.println("Would you like to play again? (yes/no): ");
String response = scanner.next();
playAgain = response.equalsIgnoreCase("yes");
} while (playAgain);
System.out.println("You won " + roundsWon + " rounds. Thanks for playing!");
scanner.close();
}
}