0

I need to print all 10 array's variables in the console, but it prints 10 times only the last one. Instead of printing all names and marks, it prints only "Jake", 74 (SEstudents[9] is initialised so). I wrote 2 classes: Student abd Tester. Student class has 2 static attributes, constructor and roString() method. Tester class has static array of Student objects and must print it. setStudents() (obviously) initialises the array and printStudents() outputs it. Why it`s done in 2 another methods: there is an obigatory task to set objects and print them in 2 separete methods that makes me a big problem...

public class Student {

    // private class fields.
    public static String PIB;
    public static int averageMark;

    // Student class constructors.
    public Student(String name, int mark){
        Student.PIB = name;
        Student.averageMark = mark;
    }

    @Override
    public String toString() {
        return "Name: "+Student.PIB+", Mark: "+Student.averageMark;
    }
}
public class Tester {

    public static Student[] SEstudents = new Student[10];
    public static void main(String[] args) {
        setStudents();
        printStudents();
    }

    public static Student[] setStudents(){

        SEstudents[0] = new Student("John", 95);
        SEstudents[1] = new Student("Micheal", 94);
        SEstudents[2] = new Student("Eve", 92);
        SEstudents[3] = new Student("Jack", 94);
        SEstudents[4] = new Student("Ann", 96);
        SEstudents[5] = new Student("Gabriel", 86);
        SEstudents[6] = new Student("John", 88);
        SEstudents[7] = new Student("Sophie", 96);
        SEstudents[8] = new Student("Tim", 73);
        SEstudents[9] = new Student("Ryan", 74);
        return SEstudents;
    }

    public static void printStudents(){
        for(Student s: SEstudents){
            System.out.println(s);
        }
    }
}

Debugging, I found out that in setStudents() method the next array's var rewrites the previous one. That's why in the end all 10 students initialised like "Name: Jake, Mark: 47". And that's why I suspect it`s because static modifier in Student class attributes (PIB, averageMark). I may be wrong...

  • There were errors in `toString()` when I clean `static` modifier in attributes. But now did everything you suggested and it`s worked. Thanks a lot. A bit shitty for me to disturb people because of such triffle – Tim Matthew Feb 10 '23 at 19:23
  • 1
    it is important to understand the difference between non-static and static members (methods and fields) (BTW you actually did a great job finding the problem) – user16320675 Feb 10 '23 at 19:25

0 Answers0