-
Notifications
You must be signed in to change notification settings - Fork 0
/
Taskno.1
60 lines (49 loc) · 2.16 KB
/
Taskno.1
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
import java.util.Scanner;
import java.util.Random;
public class NumberGuessGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int minRange = 1;
int maxRange = 100;
int attemptsLimit = 5;
int score = 0;
System.out.println("Welcome to the Number Guessing Game!");
boolean playAgain = true;
while (playAgain) {
int generatedNumber = random.nextInt(maxRange - minRange + 1) + minRange;
int attempts = 0;
boolean guessedCorrectly = false;
System.out.println("\nI've selected a number between " + minRange + " and " + maxRange + ".");
System.out.println("You have " + attemptsLimit + " attempts to guess it.");
while (attempts < attemptsLimit && !guessedCorrectly) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
scanner.nextLine();
if (userGuess == generatedNumber) {
System.out.println("Congratulations! You've guessed the correct number: " + generatedNumber);
guessedCorrectly = true;
} else if (userGuess < generatedNumber) {
System.out.println("Too low! Try a higher number.");
} else {
System.out.println("Too high! Try a lower number.");
}
attempts++;
}
if (!guessedCorrectly) {
System.out.println("Sorry, you've used all your attempts. The number was: " + generatedNumber);
}
if (guessedCorrectly) {
score++;
}
System.out.println("Your current score: " + score);
System.out.print("Do you want to play again? (yes/no): ");
String playChoice = scanner.nextLine().toLowerCase();
if (!playChoice.equals("yes")) {
playAgain = false;
System.out.println("Thanks for playing! Your final score: " + score);
}
}
scanner.close();
}
}