-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGame
More file actions
62 lines (51 loc) · 2.33 KB
/
NumberGame
File metadata and controls
62 lines (51 loc) · 2.33 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
57
58
59
60
61
62
import java.util.Random;
import java.util.Scanner;
public class NumberGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 100;
private static final int MAX_ATTEMPTS = 10;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int totalScore = 0;
int roundsPlayed = 0;
while (true) {
int targetNumber = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
int attempts = 0;
boolean guessedCorrectly = false;
System.out.println("\nRound " + (roundsPlayed + 1));
System.out.println("I've generated a number between " + MIN_NUMBER + " and " + MAX_NUMBER + ". Can you guess it?");
while (attempts < MAX_ATTEMPTS && !guessedCorrectly) {
System.out.print("Enter your guess (Attempt " + (attempts + 1) + "/" + MAX_ATTEMPTS + "): ");
int userGuess = scanner.nextInt();
attempts++;
if (userGuess == targetNumber) {
System.out.println("Congratulations! You've guessed the correct number: " + targetNumber);
guessedCorrectly = true;
} else if (userGuess < targetNumber) {
System.out.println("Too low. Try again.");
} else {
System.out.println("Too high. Try again.");
}
}
if (!guessedCorrectly) {
System.out.println("Sorry, you've run out of attempts. The correct number was: " + targetNumber);
}
int roundScore = MAX_ATTEMPTS - attempts + 1;
if (roundScore > 0) {
totalScore += roundScore;
}
roundsPlayed++;
System.out.println("Your score for this round: " + roundScore);
System.out.println("Total score: " + totalScore);
System.out.println("Rounds played: " + roundsPlayed);
System.out.print("Do you want to play again? (yes/no): ");
String playAgain = scanner.next().toLowerCase();
if (!playAgain.equals("yes")) {
break;
}
}
System.out.println("Thanks for playing! Your final score: " + totalScore);
scanner.close();
}
}