Skip to content

Commit 14b3b2b

Browse files
committed
added NumberGuess Game
1 parent c06dc29 commit 14b3b2b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.puzzlesandgames;
2+
import java.util.Scanner;
3+
4+
public class NumberGuess {
5+
public static void playGame() {
6+
Scanner sc = new Scanner(System.in);
7+
int number = (int)(Math.random() * 100) + 1;
8+
int guess = 0, tries = 0;
9+
10+
System.out.println("🎯 Welcome to the Number Guessing Game!");
11+
System.out.println("I've picked a number between 1 and 100. Try to guess it!\n");
12+
13+
while (true) {
14+
System.out.print("Enter your guess: ");
15+
16+
if (!sc.hasNextInt()) {
17+
System.out.println("Please enter a valid number.");
18+
sc.next();
19+
continue;
20+
}
21+
22+
guess = sc.nextInt();
23+
tries++;
24+
25+
if (guess < 1 || guess > 100) {
26+
System.out.println("⚠️ Please guess a number between 1 and 100.");
27+
continue;
28+
}
29+
30+
if (guess < number)
31+
System.out.println("Too low! 📉");
32+
else if (guess > number)
33+
System.out.println("Too high! 📈");
34+
else {
35+
System.out.println("🎉 Correct! The number was " + number + ".");
36+
System.out.println("You took " + tries + " tries.");
37+
break;
38+
}
39+
}
40+
41+
sc.close();
42+
}
43+
44+
public static void main(String[] args) {
45+
playGame();
46+
System.out.println("\nThanks for playing! 👋");
47+
}
48+
}

0 commit comments

Comments
 (0)