I need the user to input a number 1-5 or 9 from the keyboard and want to keep prompting until they input a correct number. Here's the code that I have:
String taskInput = kb.nextLine();
Scanner kbString = new Scanner(taskInput);
boolean validInput = false;
boolean validSelection;
while(!validInput){
validSelection = false;
while (!kbString.hasNextInt()){
System.out.print("Please enter a task number; ");
taskInput = kb.nextLine();
kbString = new Scanner(taskInput);
}
while(!validSelection){
if(kbString.hasNextInt()) {
nextTask = kbString.nextInt();
if(nextTask < 1 || (nextTask > 5 && nextTask != 9)) {
validSelection = true;
}else{
validInput = true;
validSelection = true;
}
}
}
}
This works but I find it a little confusing as we need to set validSelection = true even when the user inputs a bad number e.g. 7. Is there a cleaner way of doing this?