简体   繁体   中英

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

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.

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).

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

Couple of issues:

  1. You are missing semicolon in you println method.
  2. You are redefining the number within if
  3. you are using if which is for checking number instead use while so until and unless user enters correct number you dont proceed.

     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(); while (number <=0) { System.out.println(" please enter a valid number"); number = input.nextInt(); } input.close(); return number; } 

The classical way of doing that is to limit the number of retry and abort beyond that ::

static final int MAX_RETRY = 5; // what you want
...
int max_retry = MAX_RETRY;
int number;
while (--max_retry >= 0) {
    System.out.print("Enter the number of cookies you'd like to make ");
    number = input.nextInt();
    if (number > 0) {
        break;
    }
    System.out.println("Please enter a valid number")
}
if (max_retry == 0) {
    // abort
    throw new Exception("Invalid input");
}
// proceed with number ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM