I just started to learn Java and had to write a "guess the number" game.
Could you please review and give me some feedback?
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = nextValidInt(input);
System.out.println("Range end (inclusively):");
int endRange;
endRange = nextValidInt(input);
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = nextValidInt(input);
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange + 1)
+ startRange);
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {
int guess;
guess = nextValidInt(input);
if (guess == randNumber) {
System.out.println("Congratz - you have made it!!");
System.out.println("Goodbye");
break;
} else if (guess > randNumber) {
System.out.println("The number is smaller");
} else if (guess < randNumber) {
System.out.println("The number is higher");
}
}
if (numberOfTries >= maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
public static int nextValidInt(Scanner s) {
while (!s.hasNextInt() && s.hasNext()) {
System.out.println("Please provide a valid integer value!");
s.next();
}
return s.nextInt();
}
GuessingGame
class that handles all the logic of the game (e.g. number of guesses remaining), while leaving all the input/output inmain
, then posting that for review. \$\endgroup\$