Java 一个创造人的小程序
我想制作一个程序来创建人员并显示此类人员的列表,但不知道我是否做得很好,也不知道使用arraylist打印结果的逻辑是否有人可以帮助我?多谢各位Java 一个创造人的小程序,java,Java,我想制作一个程序来创建人员并显示此类人员的列表,但不知道我是否做得很好,也不知道使用arraylist打印结果的逻辑是否有人可以帮助我?多谢各位 package person; import java.util.*; public class Person { public int Id; public String Name; public boolean Show; public ArrayList people; public Person(
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);
}
}
谢谢 公共阵列人;不属于Person类。我建议您的客户机代码使用它来尝试类,或者创建一个从ArrayList继承的类。然后,如果愿意,可以向该类添加InsertPerson函数
我还建议对您的收藏使用ArrayList,而不是ArrayList。在这里看到一张照片。您还应该创建getter/setter方法,而不是使用公共字段
所以,你的课程是:
public class Person { // ...
public class People extends ArrayList<Person> {
public void InsertPerson(Person person) {
this.add(person);
}
// ...
问题:您正在创建arraylist people作为每个人的属性,表示每个人都有一个人员列表
快速修复:
调动公众的积极性;给你的班级。
将public void insertPerson、ArrayList列表也移动到您的Trying类中
更好的解决方案:
我建议使用PeopleManager类,它包含arraylist人员和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方法。您需要在您的试用类中创建一个PersonManager。其他人所说的都是正确的,但我认为理论上您的代码应该仍然有效。这条线有一个问题,但是
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);
}
你到底有什么问题?是什么让您认为您的代码不起作用?您可以对数组使用static属性,但我建议这样做,因为InsertPerson不是Person逻辑方法,我的意思是。。你可以。。但这不是逻辑。使用PersonManager或People类,就像他建议的那样。