2016-10-14 36 views
-1

这是一个程序,用于查明某人的年龄应该是一年中的平方根。我如何从这个循环中选择一个年龄和关联年份,以便我可以打印它?从循环中取值?

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

申报INT sqrtAge = 0之外for循环,然后指定sqrtAge = age * age;在里面 – fabricio

+0

我期待从循环中获取特定的价值(例如)年龄45 =年2025年 –

回答

1

如果你只想打印特别值满足你的上述条件,则可以使用如果循环内,代码可以是这样的:

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

} 
+0

我我希望从循环中获得特定的价值(例如)45岁= 2025年 –

+0

根据您的评论编辑我的答案。希望这可以帮助。 –

0
  1. 在循环外引入局部变量。
  2. 将它指定为if声明。
  3. breakif声明。
  4. 循环后使用局部变量。
+0

我期待从循环中获取特定的价值(例如)年龄45 =年份2025 –