Answer the question
In order to leave comments, you need to log in
How to display nested array by constructor pattern?
public class Group {
private String name;
private Student[] students;
public Group(String name, Student[]students ) {
this.name = name;
this.students = students;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Group group1 = new Group("KIT-25", new Student[]{
new Student("Max", 20),
new Student("Misha", 21),
new Student("Vitya", 19),
new Student("Alyona", 20),
new Student("Ira", 19)
});
System.out.println( ? );
Answer the question
In order to leave comments, you need to log in
Hello!
You forgot to create a getter for Student[] students
Getter get an array and iterate over it with a for loop
public class Group {
private String name;
private Student[] students;
public Group(String name, Student[]students ) {
this.name = name;
this.students = students;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student[] getStudents() {
return students;
}
public void setStudents(Student[] students) {
this.students = students;
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
class Test {
public static void main(String[] args) {
Group group1 = new Group("KIT-25", new Student[]{
new Student("Max", 20),
new Student("Misha", 21),
new Student("Vitya", 19),
new Student("Alyona", 20),
new Student("Ira", 19)
});
// Вариант №1
for (Student student : group1.getStudents()) {
System.out.println(student.getName());
}
// Вариант №2 (Stream API)
Arrays.stream(group1.getStudents()).forEach(System.out::println);
}
}
You need to add a getter for the array of students in the Group:
public String getStudents() {
return students;
}
for (Student student : group1.getStudents()) {
System.out.println( student.getName() );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question