Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop user input until conditions met

Tags:

java

I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.

    Scanner keyboard = new Scanner(System.in);
    int startr;
    int endr;
    System.out.println("Enter the Starting Number of the Range: ");
    startr=keyboard.nextInt();
    if(startr%10==0&&startr>=0){
        System.out.println("Enter the Ending Number of the Range: ");
        endr=keyboard.nextInt();
        if(endr%10==0&&endr<=1000){

        }else{
            System.out.println("Numbers is not divisible by 10");
        }
    }else{
        System.out.println("Numbers is not divisible by 10");
    }
like image 358
Student Avatar asked Dec 27 '22 06:12

Student


2 Answers

Easy with do-while:

Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
  System.out.println("Enter the Starting Number of the Range: ");
  startr = keyboard.nextInt();
  if(startr % 10 == 0 && startr >= 0)
    good = true;
  else
    System.out.println("Numbers is not divisible by 10");
}
while (!good);

good = false;
do
{
    System.out.println("Enter the Ending Number of the Range: ");
    endr = keyboard.nextInt();
    if(endr % 10 == 0 && endr <= 1000)
      good = true;
    else
      System.out.println("Numbers is not divisible by 10");
}
while (!good);

// do stuff
like image 118
Bernhard Barker Avatar answered Jan 09 '23 23:01

Bernhard Barker


You need to use a while, something like:

while conditionsMet is false
    // gather input and verify
    if user input valid then
        conditionsMet = true;
end loop

should do it.

like image 42
Ray Stojonic Avatar answered Jan 10 '23 00:01

Ray Stojonic