forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuess.java
More file actions
54 lines (44 loc) · 1.58 KB
/
NumberGuess.java
File metadata and controls
54 lines (44 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
52
53
54
/**
* Simple Number Guessing Game.
* The player guesses a random number between 1 and 100.
* Reference: https://en.wikipedia.org/wiki/Guess_the_number
*/
package com.thealgorithms.puzzlesandgames;
import java.util.Scanner;
public final class NumberGuess {
private NumberGuess() {
throw new AssertionError("Cannot instantiate NumberGuess");
}
public static void playGame() {
Scanner sc = new Scanner(System.in);
int number = (int) (Math.random() * 100) + 1;
int guess = 0;
int tries = 0;
System.out.println("🎯 Welcome to the Number Guessing Game!");
System.out.println("I've picked a number between 1 and 100. Try to guess it!\n");
while (true) {
System.out.print("Enter your guess: ");
if (!sc.hasNextInt()) {
System.out.println("Please enter a valid number.");
sc.next();
continue;
}
guess = sc.nextInt();
tries++;
if (guess < 1 || guess > 100) {
System.out.println("⚠️ Please guess a number between 1 and 100.");
continue;
}
if (guess < number) {
System.out.println("Too low! 📉");
} else if (guess > number) {
System.out.println("Too high! 📈");
} else {
System.out.println("🎉 Correct! The number was " + number + ".");
System.out.println("You took " + tries + " tries.");
break;
}
}
sc.close();
}
}