This repository was archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
50 lines (41 loc) · 1.68 KB
/
NumberGuessingGame.java
File metadata and controls
50 lines (41 loc) · 1.68 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
41
42
43
44
45
46
47
48
49
50
/*
This code below show a simple number guessing game,
Name: K V Deepak,
Task3: Number Guessing Game,
Java Internship Programming.
*/
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();
int lowerBound = 1;
int upperBound = 100; // You can adjust this range as per your preference
int targetNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I have selected a number between " + lowerBound + " and " + upperBound + ". Guess what it is!");
int attempts = 0;
boolean hasGuessedCorrectly = false;
int maxAttempts = 7; // You can adjust the maximum number of attempts here
while (attempts < maxAttempts) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
attempts++;
if (guess < targetNumber) {
System.out.println("Too low! Try again.");
} else if (guess > targetNumber) {
System.out.println("Too high! Try again.");
} else {
hasGuessedCorrectly = true;
break;
}
}
if (hasGuessedCorrectly) {
System.out.println("Congratulations! You guessed the number " + targetNumber + " correctly in " + attempts + " attempts!");
} else {
System.out.println("Sorry, you've used all your attempts. The number was: " + targetNumber);
}
scanner.close();
}
}