繁体   English   中英

如何在另一个对象数组中打印一个对象的int值?

[英]How to print the int value of an object inside another object array?

一个人如何打印另一个对象数组中一个对象的私有int数据字段。

因此,如果我有一个名为Classroom的对象和另一个名为Student的对象,该如何在Classroom对象的私有数组成员中打印出该学生对象的学生ID?

我会覆盖Student中的toString来打印studentID吗? 但是,如何在Classroom对象的数组中使用它来打印ID数组呢?

Student类中,您应该创建一个返回学生ID的方法,如以下示例所示:

class Student 
{
     private id;

     //... constructor and other code

     int getID() {return this.id;} 
}

在您的Classroom ,您应该创建一个将学生添加到学生数组中的方法(在这种情况下,我使用了ArrayList)和一个打印列表中所有学生的ID的方法。 往下看:

class Classroom
{
    private ArrayList<Student> studentsList;

    //... constructor and other code

    void addStudent(Student student) {
        this.studentsList.add(student);
    }

    void printStudentsList() {
        for(Student student: this.studentsList) {
            System.out.println(student.getID());
        }
    }
}

请注意,这只是实现所需目标的一种方法。 由于您未发布代码,因此我随即提供了您所提供的信息。

类Student {private ArrayListids;

public Student(){

    ids.add("S001");

    ids.add("S002");

}

public ArrayList<String> getID(){

    return this.ids;

}

}类ClassRoom {

public static void main(String args[]){

    Student s=new Student();

    ArrayList<String>studentID=s.getID();

    for(String id:studentID){

        System.out.println("Student ID :"+id);

    }

}

}

我认为您需要创建一些public methods来使用private attributes 我认为您可以按以下方式设计StudentClassroom班级:

class Student
{
    private int studentID;
    //and others private attributes

    public student()
    {
       //write something here to initiate new object
    }
    public int getID()
    {
        return studentID;
    }
    //you can insert others methods here
}
class Classroom
{
   private Student[] studentArray;
   //add constructer here if you need it
   public int getStudentId(int position) //get student ID at `position` in the array
   {
     return studentArray[position].getID();
   }
}
public class Main
{
    public static void main(String[]args)
    {
       Classroom classroom = new Classroom();
       //do something to insert student to array of the `classroom`

       //assume you need to get ID of student in 6th place
       System.out.println(classroom.getStudentID(6));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM