为什么"return names;" get 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;
    }
}

输出为:

null

16

您正在重新分配第二个循环中的新的User,默认情况下将name设置为null。您应该重复使用现有的User对象,例如此

for(int j = 0; j<ages.length; j++){
    users[j].setAge(ages[j]);
}

在一个循环中进行两个分配(因为数组的长度相同)

for(int i = 0; i<users.length; i++){
    User u = new User();
    u.setName(names[i]);
    users[j].setAge(ages[i]);
    users[i] = u;
}

或添加构造函数,然后将名称和年龄传递给它:

for(int i = 0; i<users.length; i++){
    User u = new User(names[i], ages[i]);
}

如果允许设置nameage,则可以使类不变,

public class User {
    final String name;
    final int age;
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
}

这是因为您已经使用第二个迭代超过了users数组中的现有对象。

for(int i = 0; i<names.length; i++){ //array is named 'names'
    User u = new User();
    u.setName(names[i]);
    users[i] = u;
}
for(int j = 0; j<ages.length; j++){
    user[i].setAge(ages[j]); // using the existing object here
}

在另一侧,我认为您将根据用户的数量为年龄映射。因此,做这样的事情应该是安全的:

if(names.length != ages.length) { 
    // input mismatch for ages and names ; do some action in this condition
} else {
    for(int i = 0; i<names.length; i++){
        users[i].setName(names[i]);
        users[i].setAge(ages[i])
    } 
}

最新更新