【问题标题】:Calling a non-static method return type void调用非静态方法返回类型 void
【发布时间】:2014-02-13 05:24:11
【问题描述】:

对于我的程序,我从命令行创建了 2 个人、姓名和年龄。然后我的程序会在一个对话框中为每个人显示一个toString。但是,我正在尝试实现两种方法来更改每个人的姓名数据字段和年龄数据字段。然后显示两个带有更改值的附加对话框。调用我的方法时,它会编辑对象而不是创建新对象。

我想知道我应该如何调用我的方法,这将创建新的 Persons?

例如我的命令行参数是: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;
   }
}

【问题讨论】:

  • 实际输出是多少?
  • @Christian 嗨,Christian,我添加了当前的输出。似乎调用我的方法只是更改当前对象而不是创建一个新对象。但是,我尝试用里面的方法创建一个新人,但因为它是无效的,我得到了一个错误:o
  • 我不明白你为什么要创建新的Persons?修改它们对我来说看起来不错。
  • @Christian 我想用新修改的人显示旧人对象。主要是为了理解调用这种类型的方法,因为我尝试了无数次尝试来创建一种在新对话框消息中输出方法的方法。
  • 我认为您能做的最好的事情就是遵循@DavidWallace 的回答。由于比尔和比尔博士是同一个人,因此将他们视为不同的人是没有意义的。

标签: java class methods void non-static


【解决方案1】:

您可以在调用birthday()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);
  }

【讨论】:

  • 嗯,有趣!我没有实现 for 循环。但是我确实创建了对 toString 的更多调用和另外两个消息对话框,现在它似乎输出正常!
猜你喜欢
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 2013-03-20
  • 2021-06-28
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多