вы можете попробовать разбить ваши коды на логические методы.
что делает ваш код более читабельным.
boolean isValidInput;
int input =-1;
Scanner scanner = new Scanner(System.in);
do{
printMenu();
input = getInt(scanner); //this will check that the input is an int
if(input >0 && input<=4) { isValidInput = true;}
else { System.out.println("selection invalid. Try again.");
}while (!isValidInput); //keeps looping until a valid input is entered.
switch(input){
case 1: ... your code logic here...
}
ниже будет, как вы пишете свои служебные методы
static void printMenu(){
System.out.println("Enter what maths to use:");
System.out.println("Enter 1 for addition");
System.out.println("Enter 2 for Subtraction");
System.out.println("Enter 3 for multiplication");
System.out.println("Enter 4 for Division");
}
не забудьте выполнить проверку ошибок, чтобы предотвратить сбой приложения при вводе пользователем строки.
static int getInt(Scanner scanner){
int result =0;
while(true){ //loop forever
try{
result=scanner.nextInt();
return result; //it will return if there's no error
}catch (Exception e){
scanner.nextLine(); //clear the scanner
System.out.println("not an integer! try again: ");
}
}
}