I'm a little confused
I created a class called person, which has age and name attributes (and get the given methods). Then in another class I want to create an array of people, where each person has a different age and name. But some, like, after all, all my faces end with a surname and age. If I manually create them, thatโs fine, but with the for loop I have this problem. What should I do to get different people?
Here is the human class code:
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) {
}
}
And here is the code where I want to create my array / matrix:
public class array {
static person[][] a;
public static void main(String[] args) {
a=new person[3][3];
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");
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());
}
}
System.out.println(a[0][0].getName()+" "+a[0][0].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());
}
}
}
}
source
share