我有点迷茫
我创建了一个名为 person 的类,它具有 age 和 name 属性(以及 get set 方法)。 然后在另一个类中,我想创建一个 persons 数组,其中每个人都有不同的年龄和姓名。 但是有些人最终如何以姓氏和年龄结尾。 如果我手动创建它们那么没关系,但是使用 for 循环我遇到了这个问题。 我应该怎么做才能得到不同的人?
这是人员类的代码:
public class person {
static String name;
static int age;
public person() {
name="name";
age=0;
}
public static String getName() {
return name;
}
public static void setName(String name) {
person.name = name;
}
public static int getAge() {
return age;
}
public static void setAge(int age) {
person.age = age;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
这是我要创建数组/矩阵的代码:
public class array {
static person[][] a;
public static void main(String[] args) {
a=new person[3][3];
//manual created person
person first=new person();
person second=new person();
person third=new person();
first.setAge(12);
first.setName("first");
second.setAge(20);
second.setName("second");
third.setAge(40);
third.setName("third");
//automatic (here I get the disired effect)
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j]=new person();
a[i][j].setAge(10+j);
a[i][j].setName("Alia"+i);
System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
}
}
// a[0][0]=first;
// a[0][1]=second;
// a[1][2]=third;
// System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
//for checking , and it doesnt work anymore
System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
// for (int i = 0; i < a.length; i++) {
// for (int j = 0; j < a.length; j++) {
// System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
// }
//
// }
getname();
}
private static void getname() {
System.err.println("get name function");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.println(a[i][j].getName());
}
}
}
}
最佳答案
从人员属性中删除 static
关键字。如果它是静态的,它会被所有实例(所有人物对象)使用。
但我会这样做:
public class Person {
public final String name;
public final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
public static void main(String... args) {
List<Person> people = new LinkedList<Person>();
people.add(new Person("David", 28));
people.add(new Person("Andreas", 27));
System.out.println(people);
}
}
关于java如何创建不同对象的数组/矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174543/