-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessTheNumber.java
More file actions
40 lines (33 loc) · 1.56 KB
/
GuessTheNumber.java
File metadata and controls
40 lines (33 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.Scanner;
import java.util.Random;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1; // Random number between 1 and 100
int numberOfTries = 0;
int userGuess = 0;
System.out.println("Welcome to the Guess the Number game!");
System.out.println("I have picked a number between 1 and 100. Try to guess it!");
// Loop until the user guesses the correct number
while (userGuess != numberToGuess) {
System.out.print("Enter your guess: ");
// Check if the input is an integer
if (scanner.hasNextInt()) {
userGuess = scanner.nextInt();
numberOfTries++;
if (userGuess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (userGuess > numberToGuess) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the right number in " + numberOfTries + " tries.");
}
} else {
System.out.println("Invalid input. Please enter an integer.");
scanner.next(); // Clear invalid input
}
}
scanner.close();
}
} do some changes for github slighly