我目前正在从事一个项目,该项目涉及创建一个程序,该程序可以输入和显示一个人的家谱。但是,在创建了一个带有构造函数的类Person和一个调用该类的方法之后,我意识到我不知道如何为调用' person‘类的方法输入适当的参数。下面是我的代码-
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的机制和基本要素的理解,因为这正是我在编码方面的雄心已经停止的地方。
不知道为什么stackOverflow将代码的前几行格式化为普通文本.
发布于 2018-04-21 20:39:24
首先,您不需要一个私有类,您可以按以下方式定义类,
public class FamilyTree {
//....
}
class Person {
//....
}在FamilyTree类中,需要有一个存储人员的结构。尽管FamilyTree是一棵树,但为了简单起见,您可以使用列表。您应该定义这个列表并在构造函数中初始化它。
public class FamilyTree {
List<Person> personList;
public FamilyTree(){
personList = new ArrayList();
}
//...
}当您想要向personList中添加一个人时,可以调用InputInformationfor方法。然而,这是一个不好的名字,海事组织,你可以说addPerson。
public void addPerson(Person person){
personList.add(person);
}最后,在main方法中,您可以先创建一个person,然后将它添加到列表中。最后的代码是这样的,
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;
}
}发布于 2018-04-21 20:34:10
您可以使用以下内容: 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;
}
}我希望这能帮到你。也许你一定要读必修课。Java是一个很好的开端。
https://stackoverflow.com/questions/49959801
复制相似问题