-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask_1_NUmber_Game.java
More file actions
51 lines (43 loc) · 1.58 KB
/
Task_1_NUmber_Game.java
File metadata and controls
51 lines (43 loc) · 1.58 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
// task_01 NUMBER GAME //
import java.util.Random;
import java.util.Scanner;
class GuessingGame {
private int numberToGuess;
private int attempts;
private int maxAttempts;
public GuessingGame(int maxAttempts) {
Random random = new Random();
numberToGuess = random.nextInt(100) + 1;
attempts = 0;
this.maxAttempts = maxAttempts;
}
public void play() {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
while (attempts < maxAttempts) {
System.out.print("Take guess no " + (attempts + 1) + ": ");
int guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("Too low!");
} else if (guess > numberToGuess) {
System.out.println("Too high!");
} else {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
scanner.close();
return;
}
}
System.out.println("Sorry, you've reached the maximum number of attempts.");
System.out.println("The number I was thinking of was: " + numberToGuess);
scanner.close();
}
}
public class Task_1_NUmber_Game {
public static void main(String[] args) {
int maxAttempts = 5; // attempts limit
GuessingGame guessingGame = new GuessingGame(maxAttempts);
guessingGame.play();
}
}