在Java简单程序中打破While循环

时间:2015-10-30 13:23:14

标签: java eclipse while-loop

所以我的最终目标是我希望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");
    }
}

3 个答案:

答案 0 :(得分:3)

while (inputErrorage) {

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


  }

你永远不会重置inputErrorAge的值,所以如果它为true,它将保持为真。

while (inputErrorage) {

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

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

应该解决它。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

根据命名,你的病情是错误的。请改为:

if(key is Array)
{
    data = set.Find((key as IEnumerable).Cast<object>().ToArray());
}
else
{
    data = set.Find(key);
}

如果输入无效年龄,则进入无限循环: 在inputErrorage条件下打破它。

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