File tree Expand file tree Collapse file tree
section-05-arrays/src/main/java Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Random ;
2+ import java .util .Scanner ;
3+
4+ public class NumberGuessingGame {
5+
6+ public static void main (String [] args ) {
7+
8+ // Initialize the game
9+
10+ int upperBound = 5 ;
11+
12+ // compute a random number between 1 and the upperBound
13+ Random random = new Random ();
14+ int secretNumber = random .nextInt (upperBound ) + 1 ;
15+
16+ int maxAttempts = 3 ;
17+
18+ System .out .println ("NUMBER GUESSING GAME" );
19+ System .out .println ("You have " + maxAttempts + " attempts." );
20+ System .out .println ();
21+
22+ Scanner scanner = new Scanner (System .in );
23+
24+ boolean won = false ;
25+
26+ // Game loop
27+ for (int i =maxAttempts ; i > 0 ; i --) {
28+
29+ // prompt the user
30+ System .out .print ("Guess a number between 1 and " + upperBound + ": " );
31+ int theGuess = scanner .nextInt ();
32+
33+ won = (theGuess == secretNumber );
34+
35+ if (won ) {
36+ System .out .println ("Success!! You guess the secret number: " + secretNumber );
37+ break ;
38+ }
39+ else {
40+ System .out .println ("Sorry, your guess is incorrect." );
41+ System .out .println ("You have " + (i -1 ) + " attempt(s) left." );
42+ System .out .println ();
43+ }
44+ }
45+
46+ // End Game Check
47+ if (!won ) {
48+ System .out .println ("You did not win. The secret number was: " + secretNumber );
49+ }
50+
51+ scanner .close ();
52+ }
53+ }
54+
55+
56+
57+
58+
59+
60+
61+
62+
63+
64+
65+
You can’t perform that action at this time.
0 commit comments