家谱,方法混乱

时间:2018-04-21 20:07:44

标签: java class methods parameters tree

我目前正在开展一个项目,该项目涉及创建一个可以输入和显示一个人的家谱的程序。但是,在创建一个名为Person的类后,用一个构造函数来设置该人的名字和一个调用该类的方法,我意识到我不知道如何为调用&#39的方法输入正确的参数。 ;人'类。这是我的代码 -

public class FamilyTree

{
    private class Person
    {
        private String name;

        public Person(String name)
        {
            this.name = name;

        }
    }
public void InputInformationfor(Person person)
{
//also do not know what would go here
}

public static void main(String[] args)
{
    FamilyTree famtree = new FamilyTree();
    famtree.InputInformationfor(??????);

}
}

任何帮助将不胜感激。我真的试图推动我对java的机制和基本要素的理解,因为这是我编码的野心肯定会停止的地方。

P.S。不知道为什么stackOverflow将我的代码的前几行格式化为普通文本...

2 个答案:

答案 0 :(得分:0)

可能你可以使用这样的东西: 1.定义Person类的变量和为人员添加信息的方法,例如:

public class Person {
      String name;
      String age;
      int age;
      String father;
      String mother;

//Define constructor
      public Person(){
      //What you want initialize.
      }

      public void setname(String nameinput){
      name = nameinput;
      }
}
  1. 定义您对家谱的理解方式,就像您为一个人所做的那样。
  2. 我会使用一个虚拟的Person类来将Persons添加到族树中。因此,在您的主要功能中,您可以将人员添加到树中。

      public static void main(String[] args){
      Person dummy = new Person();
      //Add data to the person.
      dummy.setname("Mike");
      //Add the information you want to the dummy variable.
      //Then you can add the person to the tree.
      FamilyTree famtree = new FamilyTree();
      famtree.InputInformationfor(dummy);}
    
  3. 我希望这可以帮到你。可能是你必须阅读关于课程。 Java for dummies是一个好的开始。

答案 1 :(得分:0)

首先,您不需要可以按如下方式定义类的私有类,

public class FamilyTree {
//....
}
class Person {
//....
}

在FamilyTree类中,您需要具有存储人员的结构。虽然FamilyTree是,但为简单起见,您可以使用列表。您应该定义此列表并在构造函数中初始化它。

public class FamilyTree {
    List<Person> personList;
    public FamilyTree(){
        personList = new ArrayList();
    }
    //...
}

如果要将人员添加到personList,可以调用InputInformationfor方法。但是,这是一个坏名字imo,你可以说addPerson。

public void addPerson(Person person){
    personList.add(person);
}

最后,在main方法中,您可以先创建一个人,然后将其添加到列表中。所以,最终代码看起来像这样,

import java.util.ArrayList;
import java.util.List;


public class FamilyTree {
    List<Person> personList;
    public FamilyTree(){
        personList = new ArrayList();
    }

    public void addPerson(Person person){
        personList.add(person);
    }


    public static void main(String[] args){
        FamilyTree famtree = new FamilyTree();
        Person person = new Person("Emre");
        famtree.addPerson(person);
    }
}

class Person {
    private String name;

    public Person(String name){
        this.name = name;
    }
}