File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-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+ /**
5+ * "Guess My Number" game with added fun features.
6+ */
7+ public class GuessGame {
8+
9+ public static void main (String [] args ) {
10+ Scanner scanner = new Scanner (System .in );
11+ Random random = new Random ();
12+
13+ System .out .println ("Welcome to the Guess My Number game!" );
14+ System .out .println ("I've picked a number between 1 and 100." );
15+ System .out .println ("Try to guess it!" );
16+
17+ int numberToGuess = random .nextInt (100 ) + 1 ;
18+ int attempts = 0 ;
19+ int maxAttempts = 15 ;
20+
21+ while (attempts < maxAttempts ) {
22+ System .out .print ("Enter your guess: " );
23+ int guess = scanner .nextInt ();
24+ attempts ++;
25+
26+ if (guess == numberToGuess ) {
27+ System .out .println ("Congratulations! You guessed the number in " + attempts + " attempts!" );
28+ break ;
29+ } else if (guess < numberToGuess ) {
30+ System .out .println ("Too low! Try again." );
31+ } else {
32+ System .out .println ("Too high! Try again." );
33+ }
34+ }
35+
36+ if (attempts == maxAttempts ) {
37+ System .out .println ("Oops! You've reached the maximum number of attempts." );
38+ System .out .println ("The correct number was: " + numberToGuess );
39+ }
40+
41+ scanner .close ();
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments