-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathTusharHacktoberfest6
38 lines (30 loc) · 1.44 KB
/
TusharHacktoberfest6
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
Certainly! Here's a simple Java program for a text-based guessing game called "Number Guess." In this game, the program generates a random number between 1 and 100, and the player has to guess the number.
import java.util.Scanner;
import java.util.Random;
public class NumberGuessGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int lowerBound = 1;
int upperBound = 100;
int numberToGuess = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
int numberOfTries = 0;
boolean hasGuessedCorrectly = false;
System.out.println("Welcome to the Number Guess Game!");
System.out.println("I've selected a random number between 1 and 100. Try to guess it.");
while (!hasGuessedCorrectly) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
numberOfTries++;
if (userGuess < numberToGuess) {
System.out.println("Too low! Try a higher number.");
} else if (userGuess > numberToGuess) {
System.out.println("Too high! Try a lower number.");
} else {
hasGuessedCorrectly = true;
System.out.println("Congratulations! You guessed the number " + numberToGuess + " correctly in " + numberOfTries + " tries.");
}
}
scanner.close();
}
}