-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
53 lines (46 loc) · 2.07 KB
/
NumberGuessingGame.java
File metadata and controls
53 lines (46 loc) · 2.07 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
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 lowerBound = 1;
int upperBound = 100;
int maxAttempts = 7;
int score = 0;
int roundsPlayed = 0;
String playAgain;
System.out.println("Welcome to the Number Guessing Game!");
do {
int secretNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
int attempts = 0;
boolean guessedCorrectly = false;
roundsPlayed++;
System.out.println("\nI'm thinking of a number between " + lowerBound + " and " + upperBound + ".");
System.out.println("You have " + maxAttempts + " attempts to guess it!");
while (attempts < maxAttempts) {
System.out.print("Attempt " + (attempts + 1) + ": Enter your guess: ");
int guess = scanner.nextInt();
attempts++;
if (guess == secretNumber) {
System.out.println("Correct! You guessed the number in " + attempts + " attempts.");
score++;
guessedCorrectly = true;
break;
} else if (guess < secretNumber) {
System.out.println("Too low!");
} else {
System.out.println("Too high!");
}
}
if (!guessedCorrectly) {
System.out.println("You've used all attempts. The number was: " + secretNumber);
}
System.out.println("Score: " + score + " win(s) out of " + roundsPlayed + " round(s).");
System.out.print("Do you want to play another round? (yes/no): ");
playAgain = scanner.next().toLowerCase();
} while (playAgain.equals("yes"));
System.out.println("Thanks for playing! See you next time.");
scanner.close();
}
}