John Doe
John Doe

Reputation: 121

Breaking out of While Loop in Java Simple Program

So my final goal is that I want the while loop to function only when age input is incorrect. When I put an invalid age (say 200) it prompts Enter age, but when I enter a valid age (e.g. 20) it prompts repeatedly. How do I solve this?

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    final int MIN_AGE = 18, MAX_AGE = 65, MAX_POSSIBLE_AGE = 120;
    boolean inputErrorage = false;
    int age;

    System.out.println();
    System.out.print("\tEnter your age: ");

    age = scan.nextInt();

    if (age < 0 || age > MAX_POSSIBLE_AGE) {
        inputErrorage = true;
    }

    while (inputErrorage) {
        System.out.print("\tEnter your age: ");
        age = scan.nextInt();
    }

    if (!inputErrorage) {
        System.out.println("ok");
    }
}

Upvotes: 1

Views: 252

Answers (3)

Kunjan Shah
Kunjan Shah

Reputation: 86

Your condition is wrong, according to naming. Please change to this :

if (age < 0 || age > MAX_POSSIBLE_AGE)
  inputErrorage = false;

and if you enter invalid age then it enters in infinite loop: break it on inputErrorage condition.

while (!inputErrorage) {
  System.out.print("\tEnter your age: ");
  age = scan.nextInt();
  if((age < 0 || age > MAX_POSSIBLE_AGE)){ 
    inputErrorAge = true;
  }
}

Upvotes: 0

sidgate
sidgate

Reputation: 15244

public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  final int MIN_AGE = 18, MAX_AGE = 65, MAX_POSSIBLE_AGE = 120;
  boolean inputErrorage = false;
  int age;

  System.out.println();

  while (!inputErrorage) {
    System.out.print("\tEnter your age: ");
    age = scan.nextInt();
     if (age < 0 || age > MAX_POSSIBLE_AGE)
      inputErrorage = true;
    }
   }
}

Upvotes: 1

Stultuske
Stultuske

Reputation: 9437

while (inputErrorage) {

    System.out.print("\tEnter your age: ");
      age = scan.nextInt();


  }

You never reset the value for inputErrorAge, so if it is true once, it will remain true.

while (inputErrorage) {

    System.out.print("\tEnter your age: ");
      age = scan.nextInt();

      inputErrorAge = (age < 0 || age > MAX_POSSIBLE_AGE);
  }

should solve it.

Upvotes: 3

Related Questions