一个小程序来创造人

时间:2012-05-17 19:52:06

标签: java

我想创建一个程序来创建人员并显示这些人的列表,但不知道我是否表现良好,并且使用“arraylist”打印结果任何人都无法帮助我吗?非常感谢你。

package person;
import java.util.*;

public class Person {
    public int Id;
    public String Name;
    public boolean Show;
    public ArrayList people;

    public Person(
            int identificator,
            String thename,
            boolean showornot
            ){
        this.Id = identificator;
        this.Name = thename;
        this.Show = showornot;
    }

    public void InsertPerson(Person person, ArrayList list){
        this.people = list;
        list.add(person);
    }

}

主要:

package person;
import java.util.*;


public class Trying {

    public static void main(String[] args) {
     Scanner stdin = new Scanner(System.in);
     Scanner stdin2 = new Scanner(System.in);
     Scanner stdin3 = new Scanner(System.in);
     Scanner stdin4 = new Scanner(System.in);

     ArrayList list_of_people;
     list_of_people = new ArrayList();


     int option = 0;
     int identificador = 0;
     String name = "";
     boolean show = true;    

    name = “Toni”;


         Person person1 = new Person(identificador, name, true);
         person1.InsertPerson (person1, list_of_people);
         Iterator ite = list_of_people.iterator();
         while(ite.hasNext()){
             System.out.println(list_of_people);
    }
}

谢谢!

3 个答案:

答案 0 :(得分:5)

问题:您正在创建arraylist“people”作为每个“人”的属性(说,每个人都有一个人的列表)

<强>的QuickFix:public ArrayList people;移至试用课程。 将public void InsertPerson(Person person, ArrayList list)移至您的Trying课程。

更好的解决方法: 我建议使用PeopleManager类 - 其中包含arraylist“people”和InsertPerson方法。然后,您使用尝试中的 PeopleManager 来构建人员列表。

public class PersonManager
{
    ArrayList<Person> people;

  public PersonManager()
  {
      people = new ArrayList<Person>();
  }

  public void InsertPerson(Person person)
  {
      people.add(person);
  }     
}

然后,您可以从Person中删除arraylist,从Person中删除InsertPerson方法。您需要在Trying类中创建PersonManager。

答案 1 :(得分:1)

public ArrayList people;不属于Person类。我建议使用它的客户端代码(Trying类)或创建一个继承自ArrayList的类People。如果愿意,您可以将InsertPerson函数添加到该类。

我还建议为您的集合使用ArrayList而不是ArrayList。在此处查看generic collections tutorial。您还应该创建getter / setter moethods而不是使用公共字段。

所以,你的课程将是:

public class Person { // ...

public class People extends ArrayList<Person> {
    public void InsertPerson(Person person) {
        this.add(person); 
    }
 // ...

答案 2 :(得分:1)

其他人说的是真的,但我认为理论上你的代码应该仍然有效。但是这条线有问题......

while(ite.hasNext()){
    System.out.println(list_of_people);
}

您每次迭代都输出整个列表,可能是无限循环。把它改成这样的......

while(ite.hasNext()){
    Person curPerson = (Person)ite.next(); 
    System.out.println(curPerson.Name);
}

稍微更优雅的解决方案是抛弃迭代器以获得foreach循环...

for (Person person : list_of_people) {
    System.out.println(person.Name);
}