Java 调用非静态方法返回类型void
对于我的程序,我从命令行创建了两个人,名字和年龄。然后,我的程序将在对话框中为每个人显示一个Java 调用非静态方法返回类型void,java,class,methods,void,non-static,Java,Class,Methods,Void,Non Static,对于我的程序,我从命令行创建了两个人,名字和年龄。然后,我的程序将在对话框中为每个人显示一个toString。但是,我尝试实现两种方法来更改每个人的姓名数据字段和年龄数据字段。然后显示两个附加对话框,其中包含更改的值。调用我的方法时,它会编辑对象,而不是创建新的对象 我想知道我应该如何调用我的方法,这将创建新的人 例如,我的命令行参数是:Bill58 Miley 21 我的输出: Dr. Bill is 59 years old. Dr. Miley is 22 years old. 预期输
toString
。但是,我尝试实现两种方法来更改每个人的姓名数据字段和年龄数据字段。然后显示两个附加对话框,其中包含更改的值。调用我的方法时,它会编辑对象,而不是创建新的对象
我想知道我应该如何调用我的方法,这将创建新的人
例如,我的命令行参数是:Bill58 Miley 21
我的输出:
Dr. Bill is 59 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;
}
}
在调用
birth()
或phd()
之前,可以再插入两个对toString()
的调用,以获得指定的输出
// 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);
}
实际输出是多少?@Christian嗨,Christian,我添加了当前输出。调用我的方法似乎只是更改当前对象,而不是创建新对象。但是,我试着用里面的方法创建一个新的person,但是因为它是无效的,所以我得到了一个错误:oI不明白为什么要创建新的
person
s?修改它们对我来说很合适。@Christian我想用新修改的person显示old person对象。主要是为了理解调用这种类型的方法,因为我尝试了无数次,试图创建一种在新的对话框消息中输出方法的方法。我认为您最好遵循@DavidWallace answer。因为比尔和比尔博士是同一个人,所以把他们当作不同的人来对待是没有意义的。嗯,很有趣!我没有实现for循环。然而,我确实创建了更多对toString的调用和两个消息对话框,现在输出似乎很好!
// 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);
}