File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
src/main/java/com/thealgorithms/puzzlesandgames Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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 ("\n Thanks for playing! 👋" );
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments