[英]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
。 我認為您可以按以下方式設計Student
和Classroom
班級:
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.