所以我的最终目标是我希望while循环仅在年龄输入不正确时起作用。
当我输入无效的年龄(例如200)时,会提示输入年龄,但是当我输入有效的年龄(例如20)时,会反复提示。我该如何解决?

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

最佳答案

while (inputErrorage) {

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


  }


您永远不会重置inputErrorAge的值,因此,如果一次为true,则它将保持为true。

while (inputErrorage) {

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

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


应该解决它。

09-25 20:38