我是Java新手,很抱歉这个愚蠢的问题。
我创建了一个名为Age的课程,作为退休计划课程的一部分。在该程序的主要方法中,如何使用JOptionPane通过创建的Age类中的setStartingAge和setRetirementAge方法来询问和设置其当前年龄和所需的退休年龄。
例如,这是创建的Age类:
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();
}
}
在主要方法中,我想做类似
的事情 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);
如何修改上面的代码以使两个输入对话框将用户的输入传递给Age类中的setStarting age和setRetirementAge?
-RR
答案 0 :(得分:1)
JOptionPane.showInputDialog返回您输入的字符串。您只需获取此字符串并将其转换为整数(如果可能)。
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);
}