Skip to content

Commit e92f51b

Browse files
authored
Merge pull request #1 from kylewehrung/java-practice
Now we're talking, some similarities to python
2 parents 8f195b7 + 1170db8 commit e92f51b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

ch03/GuessGame.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)