-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberGuessGame.java
54 lines (45 loc) · 1.35 KB
/
NumberGuessGame.java
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
package oop;
import java.util.Scanner;
import java.util.Random;
class NumberGuessGame {
private int number;
private int attempts;
public NumberGuessGame() {
Random random = new Random();
number = random.nextInt(100);
}
public void play() {
System.out.println("Welcome to the Number Guessing Game!");
while (true) {
int userInput = getUserInput();
attempts++;
if (isCorrectNumber(userInput)) {
System.out.println("Congratulations! Your guess is correct. The number was " + number);
System.out.println("You attempted " + attempts + " times.");
break;
}
}
}
private int getUserInput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your guess: ");
int userInput = scanner.nextInt();
return userInput;
}
private boolean isCorrectNumber(int userInput) {
if (userInput == number) {
return true;
} else if (userInput > number) {
System.out.println("Very High");
} else {
System.out.println("Very Low");
}
return false;
}
}
public class ExerciseGuess {
public static void main(String[] args) {
NumberGuessGame game = new NumberGuessGame();
game.play();
}
}