0

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?

DCR
  • 14,737
  • 12
  • 52
  • 115
  • 1
    Does anything on the following page help? https://stackoverflow.com/questions/26446599/how-to-use-java-util-scanner-to-correctly-read-user-input-from-system-in-and-act – Old Dog Programmer Dec 17 '22 at 22:58
  • roflol. That's like asking someone the meaning of life and being given the entire encyclopedia. No, that was NOT helpful. See my answer below. Thanks for the reference. – DCR Dec 17 '22 at 23:05

1 Answers1

1

here's what I've come up with as a better way:

boolean valid = false;
while (!valid) {            
        valid = kb.hasNextInt() ;
        if (valid) {
            nextTask = kb.nextInt();
            if(nextTask < 1 || (nextTask > 5 && nextTask != 9)) {
                System.out.print("please enter task number (1-5, or 9); ");
                valid = false;
            }
        }
        else {
            System.out.print("Please enter a valid number");
        }
        kb.nextLine();
}
DCR
  • 14,737
  • 12
  • 52
  • 115