I'm new to Java, so sorry for the dumb question.
I created a class called Age to be a part of a Retirement Planning program. In the main method of the program, how do I use JOptionPane to ask and set their current age and desired retirement age with the setStartingAge and setRetirementAge methods from the created Age class.
For example, here's the created Age class:
public class Age
{
private int yearsToRetirement;
private int STARTING_AGE;
private int RETIREMENT_AGE;
public Age()
{
STARTING_AGE = 0;
RETIREMENT_AGE = 0;
}
// Parameterized Constructor
public Age(int sa, int ra)
{
setStartingAge(sa);
setRetirementAge(ra);
}
public int getStartingAge()
{
return STARTING_AGE;
}
public int getRetirementAge()
{
return RETIREMENT_AGE;
}
public int getYearsToRetire()
{
yearsToRetirement = RETIREMENT_AGE - STARTING_AGE;
return yearsToRetirement;
}
public void setStartingAge(int sa)
{
if (sa > 0)
{
STARTING_AGE = sa;
}
else
{
STARTING_AGE = 0;
}
}
public void setRetirementAge(int ra)
{
if (ra > STARTING_AGE)
{
RETIREMENT_AGE = ra;
}
else
{
RETIREMENT_AGE = 0;
}
}
public String toString()
{
return "Starting Age: " + getStartingAge()
+ "\nRetirement Age: " + getRetirementAge()
+ "\nYears until retirement: " + getYearsToRetire();
}
}
In the main method, I want to do something like
Age age = new Age();
JOptionPane.showInputDialog("Enter your current age in years(ex: 21):");
JOptionPane.showInputDialog("Enter the age you wish to retire at:");
JOptionPane.showMessageDialog(null, age);
How do I modify the above code to get the two input dialogs to pass the input from the user to setStarting age and setRetirementAge in the Age class?
-RR
JOptionPane.showInputDialog returns the string you entered. You just have to get this string and transforms it to an integer (if possible).
public static void main(String[] args) {
Age age = new Age();
String startingAgeAsString = JOptionPane.showInputDialog("Enter your current age in years(ex: 21):");
String retirementAgeAsString = JOptionPane.showInputDialog("Enter the age you wish to retire at:");
try {
age.setStartingAge(Integer.parseInt(startingAgeAsString));
} catch (NumberFormatException e) {}
try {
age.setRetirementAge(Integer.parseInt(retirementAgeAsString));
} catch (NumberFormatException e) {}
JOptionPane.showMessageDialog(null, age);
}