DCR
DCR

Reputation: 15665

java get correct input from keyboard

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?

Upvotes: 0

Views: 61

Answers (1)

DCR
DCR

Reputation: 15665

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();
}

Upvotes: 1

Related Questions