对于我的程序,我从命令行创建了2个人,姓名和年龄。然后我的程序将在每个人的对话框中显示toString
。但是,我正在尝试实现两个方法来更改每个人的名称数据字段和年龄数据字段。然后显示两个带有更改值的附加对话框。在调用我的方法时,它会编辑对象而不是创建新对象。
我想知道如何调用我的方法,这将创建新人?
例如我的命令行参数是:Bill 58 Miley 21
我的输出:
Dr. Bill is 59 years old.
Dr. Miley is 22 years old.
预期输出(对话框):
Bill is 58 years old.
Dr. Bill is 59 years old.
Miley is 21 years old.
Dr. Miley is 22 years old.
这样会弹出4个对话框。
我的代码:
import javax.swing.JOptionPane;
public class PersonMethods{
public static void main(String[] args){
Integer age1 = new Integer(0);
Integer age2 = new Integer(0);
age1 = Integer.parseInt(args[1]);
age2 = Integer.parseInt(args[3]);
// Create Person Objects
Person p1 = new Person(args[0], age1);
Person p2 = new Person(args[2], age2);
p1.phd();
p1.birthday();
p2.phd();
p2.birthday();
String firstOutput = p1.toString();
String secondOutput = p2.toString();
//Display a mesage panel in the center of the screen
JOptionPane.showMessageDialog(null, firstOutput);
JOptionPane.showMessageDialog(null, secondOutput);
}
}
// Stores the name and age for a Person
class Person{
// Data fields
private String name;
private Integer age;
public Person(String n1, int a1){
name = n1;
age = a1;
}
// Add Dr to name
public void phd(){
name = "Dr. "+name;
}
// Add one to age
public void birthday(){
age = age+1;
}
public String toString(){
String output = name + " is " + age + " years old.";
return output;
}
}
答案 0 :(得分:2)
在致电toString()
或birthday()
之前,您可以再向phd()
拨打两次电话,以获取您指定的输出。
// Create Person Objects
Person p1 = new Person(args[0], age1);
Person p2 = new Person(args[2], age2);
String[] outputs = new String[4];
outputs[0] = p1.toString();
outputs[1] = p2.toString();
p1.phd();
p1.birthday();
p2.phd();
p2.birthday();
outputs[2] = p1.toString();
outputs[3] = p2.toString();
//Display a mesage panel in the center of the screen
for (String output : outputs) {
JOptionPane.showMessageDialog(null, output);
}