我有兩個數組和兩個類。我需要輸出一個用戶的姓名和年齡,但由於返回null,所以我遇到了「姓名」的問題。 「年齡」工作正常。我的錯誤在哪裏?爲什麼「返回姓名」是空的?
public class Lesson4OOP {
public static void main(String[] args) {
String[] names = {"Adam","Sara", "Mike" , "David"};
int[] ages = {21, 25, 34, 16};
User[] users = new User[names.length];
for(int i = 0; i<users.length; i++){
User u = new User();
u.setName(names[i]);
users[i] = u;
}
for(int j = 0; j<ages.length; j++){
User a = new User();
a.setAge(ages[j]);
users[j] = a;
}
System.out.println(users[3].getName());
System.out.println(users[3].getAge());
}
}
public class User {
String names;
int ages;
public void setName(String val){
names = val;
}
public String getName(){
return names;
}
public void setAge(int num){
ages = num;
}
public int getAge(){
return ages;
}
}
輸出是:
空
爲什麼要創建8個用戶,4個名稱和4個年齡段? – John3136