Seamus W Seamus W - 1 month ago 9
Java Question

Taking a value out of a loop?

This is a program to find out what age someone would have to be for their age to be the square root of the year. How do I take an age and the associating year out of this loop so that I can print it? Thanks.

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

}


}

}

Answer

If you want to print only particular values satisfying your above condition , you can use an if inside the loop, The code can be like:

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


    }