Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Game.java #689

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Game.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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;
int numberToGuess = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
int numberOfAttempts = 0;
boolean hasGuessedCorrectly = false;

System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I have selected a number between " + lowerBound + " and " + upperBound + ". Can you guess it?");

while (!hasGuessedCorrectly) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
numberOfAttempts++;

if (userGuess < lowerBound || userGuess > upperBound) {
System.out.println("Please enter a number between " + lowerBound + " and " + upperBound + ".");
} else if (userGuess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (userGuess > numberToGuess) {
System.out.println("Too high! Try again.");
} else {
hasGuessedCorrectly = true;
System.out.println("Congratulations! You guessed the number in " + numberOfAttempts + " attempts.");
}
}

scanner.close();
}
}