-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber Guessing Game.TXT
More file actions
36 lines (28 loc) · 1.14 KB
/
Number Guessing Game.TXT
File metadata and controls
36 lines (28 loc) · 1.14 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
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("Welcome to the Number Guessing Game!");
int targetNumber = random.nextInt(100) + 1; // Generate a random number between 1 and 100
int userGuess;
System.out.println("Try to guess the number between 1 and 100.");
int attempts = 0;
boolean hasGuessedCorrectly = false;
while (!hasGuessedCorrectly) {
System.out.print("Enter your guess: ");
userGuess = scanner.nextInt();
attempts++;
if (userGuess == targetNumber) {
hasGuessedCorrectly = true;
System.out.println("Congratulations! You guessed the correct number in " + attempts + " attempts.");
} else if (userGuess < targetNumber) {
System.out.println("Too low. Try again!");
} else {
System.out.println("Too high. Try again!");
}
}
scanner.close();
}
}