Untitled
unknown
java
2 years ago
2.3 kB
7
Indexable
package org.example;
import java.util.*;
public class Main {
public static final int MAX_NUMBER = 1000;
public static final int MAX_TRIES = 7;
public static boolean isGuessValid(int guess) {
return 0 <= guess && guess <= MAX_NUMBER;
}
public static int getGuess(String text) {
Scanner scanner = new Scanner(System.in);
while (true) {
int number;
System.out.print(text);
String input = scanner.nextLine().strip();
try {
number = Integer.parseInt(input);
} catch (NumberFormatException ignored) {
System.out.println("You can only enter a number, try again...");
continue;
}
if (!isGuessValid(number)) {
System.out.println("You can only guess between 0 and " + MAX_NUMBER + ", try again...");
continue;
}
return number;
}
}
public static void main(String[] args) {
int numberToGuess = new Random().nextInt(MAX_NUMBER+1);
boolean playerGuessedCorrect = false;
for (int i = 1; i <= MAX_TRIES; i++) {
String ordinal = i == 1 ? "1st" : i == 2 ? "2nd" : i == 3 ? "3rd" : i + "th";
int playerGuess = getGuess("Enter your " + ordinal + " guess: ");
int difference = playerGuess > numberToGuess ? playerGuess - numberToGuess : numberToGuess - playerGuess;
String feedback = null;
if (playerGuess > numberToGuess) {
feedback = difference >= 300 ? "very high" : difference >= 150 ? "high" : "little high";
} else if (playerGuess < numberToGuess) {
feedback = difference >= 300 ? "very low" : difference >= 150 ? "low" : "little low";
} else {
playerGuessedCorrect = true;
break;
}
System.out.println("Your guess was '" + feedback + "'");
System.out.println();
}
if (playerGuessedCorrect) {
System.out.print("Congratulations, your guess was correct! ");
} else {
System.out.print("You've unfortunately ran out of attempts... ");
}
System.out.println("The number was '" + numberToGuess + "'");
}
}Editor is loading...
Leave a Comment