Skip to content

Commit 0f9c17b

Browse files
Merge pull request #291 from nikcode9/patch-2
Create guessnumber.java
2 parents c3e04e4 + 90bc4cb commit 0f9c17b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

guessnumber.java

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

0 commit comments

Comments
 (0)