-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
65 lines (46 loc) · 1.86 KB
/
Main.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// Generate a random number between 1 and 100
int randomNumber = (int) (Math.random() * 100) + 1;
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Start the game loop
boolean guessedCorrectly = false;
int numberOfAttempts = 0;
System.out.println("Guess a number between 1 and 100: "
+ "\nSystem Generated Number is "+randomNumber);
while (!guessedCorrectly && numberOfAttempts < 3)
{
// Prompt the user to guess a number
// Get the user's guess
int userGuess = scanner.nextInt();
// Check if the user guessed correctly
if (userGuess == randomNumber)
{
guessedCorrectly = true;
}
else
{
numberOfAttempts++;
if (userGuess > randomNumber)
{
System.out.println("Your guess is too high.");
} else
{
System.out.println("Your guess is too low.");
}
}
}
// Close the Scanner object
scanner.close();
// If the user guessed correctly, congratulate them. Otherwise, tell them the correct answer.
if (guessedCorrectly)
{
System.out.println("Congratulations! You guessed correctly! The number was " + randomNumber);
} else
{
System.out.println("Sorry, you ran out of guesses. The correct answer was " + randomNumber);
}
}
}