从循环中取出一个值?

时间:2016-10-14 15:33:04

标签: java loops math

这是一个计划,以确定他们的年龄应该是什么年龄才能成为年度的平方根。如何从这个循环中取出年龄和关联年份以便我可以打印它?

package squareAges;

import javax.swing.JOptionPane;
import java.util.Scanner;
import java.lang.Math;

public class SquareAges {

    public static final int MIN_YEAR = 1893;
    public static final int MAX_YEAR = 2139;

    public static void main(String[] args) {

        for (int age = 0; age <= 123; age++) {
            System.out.println(age + "= " + age * age + " ");

            if (MIN_YEAR <= (age * age) && (age * age) <= MAX_YEAR) {
                JOptionPane.showMessageDialog(null, "It is possible that someone  alive   today "
                        + "has, is, or will be     alive in a year that is the square of their age.");
            }
        }
    }
}

感谢。

2 个答案:

答案 0 :(得分:1)

如果您只想打印满足上述条件的特定值,可以在循环中使用 if ,代码可以是:

int age, year;
for (year = 1893; year <= 2139; year++) {
    for (age = 0; age <= 123; age++) {
        System.out.println(age + "= " + age * age + " ");

        if (MIN_YEAR <= (age * age) && (age * age) <= MAX_YEAR) {
            JOptionPane.showMessageDialog(null, "It is possible that someone  alive   today "
                    + "has, is, or will be     alive in a year that is the square of their age.");

            if (age * age == year) {
                System.out.println("Age is:" + age + "Year is:" + year);
            }
        }
    }

}

答案 1 :(得分:0)

  1. 在循环外引入局部变量。
  2. if语句中分配。
  3. break声明中的if
  4. 循环后使用局部变量。