Java将对象的变量插入到数组中

时间:2016-03-18 18:45:10

标签: java arrays object

我到处搜索,但我找不到任何东西。我们认为我们有一个学生班,这个班有两个变量:名字和成绩。我想将创建的对象的名称插入数组(只有数组没有arraylist)。我怎么能这样做?

public class Student {

    String name;
    int grade;
    public Student(String name, int grade) {
        this.name=name;
        this.grade=grade;
    }
   public String toString()
   {
       return "name:"+this.name+"grade:"+this.grade;
   }
}

public class Demo {
    public static void main(String[]args)
    {
           Student s1=new Student("Jason",73);
           Student s2=new Student("Ricky",64);
           Student s3=new Student("Mark",53);
    }
}    

3 个答案:

答案 0 :(得分:4)

通过getter返回属性值始终是一个好习惯。在Student类中创建一个getter方法并访问它以获取名称

public class Student {
    private String name;
    private int grade;

    public String getName() {
        return name;
    }

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }

    public String toString() {
        return "name:" + this.name + "grade:" + this.grade;
    }
}

public static void main(String[]args) {
    Student s1 = new Student("Jason", 73);
    Student s2 = new Student("Ricky", 64);
    Student s3 = new Student("Mark", 53);
    String[] names = {s1.getName(), s2.getName(), s3.getName()};
}

答案 1 :(得分:0)

您可以声明一个String数组,并将其值设置为:

public class Demo {
    public static void main(String[]args)
    {
           Student s1=new Student("Jason",73);
           Student s2=new Student("Ricky",64);
           Student s3=new Student("Mark",53);

           String[] studentNamesArray = {s1.name, s2.name, s3.name};
    }
}    

确保你的name财产是可以访问的,如果不是,你应该通过getter来实现:

public string getName() { return this.name }

Student课程中。

答案 2 :(得分:0)

下一个怎么样:

String[] arrayNames = {s1.name, s2.name, s3.name} 

请仔细检查您的姓名属性是否可访问。通常你可以为它做一个getter(public String getName(){return this.name}),或者声明它是公共的。请注意默认的访问修饰符/访问修饰符:https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html