I was given a homework assignment to code a console Guess the Number Game, where the user should guess a random number. Also, I had to code a simple menu with switch where I can change a random number origin/bound and attempts amount.
Please, give me some tips how could I improve the code and where I'm wrong.
P.S. I must not use classes / methods etc. Only Control Flow Statements.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
var scanner = new Scanner(System.in);
var origin = 0;
var bound = 100;
var attempts = 10;
System.out.println("Guess the Number Game!");
while (true) {
System.out.println();
System.out.println("1. Start new game.");
System.out.println("2. Change origin (" + origin + ").");
System.out.println("3. Change bound (" + bound + ").");
System.out.println("4. Change attempts amount (" + attempts + ").");
System.out.println("5. Quit.");
System.out.println();
switch (Integer.parseInt(scanner.nextLine())) {
case 1:
var number = ThreadLocalRandom.current().nextInt(origin, bound);
var currentAttempts = attempts;
System.out.println("Guess the number between " + origin + " and " + bound + "!");
while (currentAttempts > 0) {
System.out.println(currentAttempts-- + " attempts left:");
var input = Integer.parseInt(scanner.nextLine());
if (input == number)
break;
else
System.out.println("The number is " + (input < number ? "greater" : "less") + " than yours.");
}
if (currentAttempts > 0)
System.out.println("You win! Congratulations!");
else {
System.out.println("You loose! Better luck next time!");
System.out.println("The number was " + number);
}
break;
case 2:
while (true) {
System.out.println("Enter new origin:");
int newOrigin = Integer.parseInt(scanner.nextLine());
if (newOrigin < bound) {
origin = newOrigin;
break;
} else
System.out.println("Origin should be less than bound. Try again.");
}
break;
case 3:
while (true) {
System.out.println("Enter new bound:");
int newBound = Integer.parseInt(scanner.nextLine());
if (newBound > origin) {
bound = newBound;
break;
} else
System.out.println("Bound should be greater than origin. Try again.");
}
break;
case 4:
while (true) {
System.out.println("Enter new attempts amount:");
int newAttempts = Integer.parseInt(scanner.nextLine());
if (newAttempts > 0) {
attempts = newAttempts;
break;
} else
System.out.println("Attempts amount should be greater than 0. Try again.");
}
break;
case 5:
System.out.println("Bye!");
return;
}
}
}
}