0

我想制作一个程序来创建人员并显示这些人员的列表,但不知道我是否做得很好,也没有使用“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);
    }
}

谢谢!

4

3 回答 3

5

问题:您正在创建数组列表“人”作为每个“人”的属性(也就是说,每个人都有一个人列表)

Quickfix:转到public ArrayList people;您的 Trying课程。也转到您的Trying 课程。public void InsertPerson(Person person, ArrayList list)

更好的解决方法: 我建议使用 PeopleManager 类——它包含数组列表“人”和 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。

于 2012-05-17T19:55:53.337 回答
1

What everyone else is saying is true, but I think theoretically your code should still work. There is a problem with this line however...

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

You are outputting the whole list every iteration and probably infinite looping. Change it to something like this...

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

A slightly more elegant solution is to ditch the iterator for a foreach loop...

for (Person person : list_of_people) {
    System.out.println(person.Name);
}
于 2012-05-17T19:59:54.800 回答
1

public ArrayList people;不属于 Person 类。我建议使用您的客户端代码(Trying 类)或创建一个继承自 ArrayList 的类 People。然后,您可以根据需要向该类添加一个 InsertPerson 函数。

我还建议为您的集合使用 ArrayList 而不是 ArrayList。在此处查看通用集合教程。您还应该创建 getter/setter 方法,而不是使用公共字段。

因此,您的课程将是:

public class Person { // ...

public class People extends ArrayList<Person> {
    public void InsertPerson(Person person) {
        this.add(person); 
    }
 // ...
于 2012-05-17T19:55:05.060 回答