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?

2
  • 1
    Does anything on the following page help? stackoverflow.com/questions/26446599/… Commented Dec 17, 2022 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. Commented Dec 17, 2022 at 23:05

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.