-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
75 lines (54 loc) · 2.49 KB
/
Copy pathNumberGuessingGame.java
File metadata and controls
75 lines (54 loc) · 2.49 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
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.Scanner;
public class NumberGuessingGameRefactored {
private static final int MIN_RANGE = 1;
private static final int MAX_RANGE = 100;
private static final int MAX_ATTEMPTS = 10;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalScore = 0;
boolean keepPlaying;
System.out.println("### Welcome to the Modular Number Guessing Game! ###");
do {
totalScore += playRound(scanner);
keepPlaying = askToPlayAgain(scanner);
} while (keepPlaying);
System.out.println("\nGame over. Your final cumulative score is: " + totalScore);
scanner.close();
}
private static int playRound(Scanner scanner) {
int targetNumber = (int) (Math.random() * (MAX_RANGE - MIN_RANGE + 1)) + MIN_RANGE;
int attemptsUsed = 0;
boolean isCorrect = false;
System.out.println("\nNew number generated (" + MIN_RANGE + "-" + MAX_RANGE + "). You have " + MAX_ATTEMPTS + " attempts.");
do {
System.out.print("Enter your guess: ");
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a number.");
scanner.next();
}
int guess = scanner.nextInt();
attemptsUsed++;
if (guess == targetNumber) {
System.out.println("Correct! The number was " + targetNumber + ".");
System.out.println("Attempts used: " + attemptsUsed);
isCorrect = true;
} else {
String feedback = (guess < targetNumber) ? "Too low!" : "Too high!";
System.out.println(feedback + " (Attempts left: " + (MAX_ATTEMPTS - attemptsUsed) + ")");
}
} while (!isCorrect && attemptsUsed < MAX_ATTEMPTS);
if (!isCorrect) {
System.out.println("Out of attempts! The number was: " + targetNumber);
return 0;
}
return calculateScore(attemptsUsed);
}
private static int calculateScore(int attempts) {
return (MAX_ATTEMPTS - attempts) + 1;
}
private static boolean askToPlayAgain(Scanner scanner) {
System.out.print("\nPlay again? (y/n): ");
String response = scanner.next();
return response.equalsIgnoreCase("y") || response.equalsIgnoreCase("yes");
}
}