Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i prompt a user to re enter their input value, if the value is invalid?

Tags:

java

public int inputNumber() { 
    Scanner input = new Scanner (System.in);
    System.out.print("Enter the number of cookies you'd like to make ");
    int number = input.nextInt();
    if (number <=0) {
       System.out.println(" please enter a valid number")
       int number = input.nextInt(); 
    }
    input.close();
    return number;
}

EDIT:

I should have used a while loop.. throwback to literally my first project.

like image 538
Too lanky Avatar asked Mar 18 '23 03:03

Too lanky


2 Answers

System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();

while(number<=0) //As long as number is zero or less, repeat prompting
{
    System.out.println("Please enter a valid number:");
    number = input.nextInt();    
}

This is about data validation. It can be done with a do-while loop or a while loop. You can read up on topics of using loops.

Remarks on your codes: You shouldn't declare number twice. That is doing int number more than once in your above codes (which is within same scope).

like image 145
user3437460 Avatar answered Mar 26 '23 01:03

user3437460


This way you have fewer superfluous print statements and you don't need to declare you variable multiple times.

public int inputNumber() {

    Scanner input = new Scanner (System.in);
    int number = 0;

    do {
        System.out.print("Enter the number of cookies you'd like to make ");
        number = input.nextInt();
    } while(number <= 0);

    input.close();
    return number;
}
like image 39
user3270760 Avatar answered Mar 26 '23 01:03

user3270760