For my program I'm creating 2 people, names and ages from the command-line. Then my program will display a toString
in a dialog box for each person. However, I'm trying to implement two methods that changes the name data field and the age data field of each person. Then display two additional dialog boxes with the changed values. When calling my method it edits the object instead of creating a new ones.
I'm wondering how I should go about calling my methods, which will create new Persons?
For example my command-line arguments are: Bill 58 Miley 21
My output:
Dr. Bill is 59 years old.
Dr. Miley is 22 years old.
Expected Output (Dialog Boxes):
Bill is 58 years old.
Dr. Bill is 59 years old.
Miley is 21 years old.
Dr. Miley is 22 years old.
So 4 dialog boxes will pop up.
My code:
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;
}
}
You could insert two more calls to toString()
before you call birthday()
or phd()
, to get the output you've specified.
// 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.