-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathrandom.py
31 lines (26 loc) · 1.06 KB
/
random.py
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
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1; // Random number between 1 and 100
Scanner scanner = new Scanner(System.in);
int userGuess = 0;
int attempts = 0;
System.out.println("Welcome to the Guess the Number Game!");
System.out.println("I'm thinking of a number between 1 and 100. Can you guess it?");
while (userGuess != numberToGuess) {
System.out.print("Enter your guess: ");
userGuess = scanner.nextInt();
attempts++;
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 number in " + attempts + " attempts.");
}
}
scanner.close();
}
}