这是一个计划,以确定他们的年龄应该是什么年龄才能成为年度的平方根。如何从这个循环中取出年龄和关联年份以便我可以打印它?
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.");
}
}
}
}
感谢。
答案 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)
if
语句中分配。 break
声明中的if
。