File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Random ;
2+ import java .util .Scanner ;
3+
4+ public class GuessTheNumberGame {
5+ public static void main (String [] args ) {
6+ Scanner scanner = new Scanner (System .in );
7+ Random random = new Random ();
8+
9+ int lowerBound = 1 ;
10+ int upperBound = 100 ;
11+ int numberToGuess = random .nextInt (upperBound - lowerBound + 1 ) + lowerBound ;
12+ int numberOfTries = 0 ;
13+ boolean hasGuessedCorrectly = false ;
14+
15+ System .out .println ("Welcome to the Guess the Number Game!" );
16+ System .out .println ("I have selected a random number between " + lowerBound + " and " + upperBound + "." );
17+
18+ while (!hasGuessedCorrectly ) {
19+ System .out .print ("Enter your guess: " );
20+ int userGuess = scanner .nextInt ();
21+ numberOfTries ++;
22+
23+ if (userGuess < lowerBound || userGuess > upperBound ) {
24+ System .out .println ("Please guess a number within the specified range." );
25+ } else if (userGuess < numberToGuess ) {
26+ System .out .println ("The number is higher. Try again." );
27+ } else if (userGuess > numberToGuess ) {
28+ System .out .println ("The number is lower. Try again." );
29+ } else {
30+ hasGuessedCorrectly = true ;
31+ System .out .println ("Congratulations! You've guessed the number in " + numberOfTries + " tries." );
32+ }
33+ }
34+
35+ scanner .close ();
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments