-1

This program used two different classes, one that contained variables and another one that used that class as an array. When printing the array the output gives

[Student@7e0ea639, Student@3d24753a, Student@59a6e353, Student@7a0ac6e3, Student@71be98f5] even when using Arrays.toString(); How can I print the data in the arrays?

import java.util.Arrays;
public class School {
static int sum=0;
static int avg=0;
static int count=0;
static int count1=0;
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.println("How many students do you have");
        int stud=sc.nextInt();
        Student[]arr= new Student[stud];
        for(int i=0;i<arr.length;i++) {
            arr[i]= new Student();
            System.out.println("Enter The student Id");
            arr[i].id=sc.nextInt();
            String s=sc.nextLine();
            System.out.println("Enter the student name");
            arr[i].name=sc.next();
            System.out.println("Enter the student mark");
            arr[i].mark=sc.nextInt();
        }
        System.out.println("The average mark is "+avg(arr));
        System.out.println("The amount of students that passed are "+pass(arr));
        System.out.println("The amount of students that failed are "+fail(arr));
        System.out.println("This is the data of all students:");
        System.out.println(Arrays.toString(arr));
    }
    
    public static int avg(Student[]arr) {
        for(int i=0;i<arr.length;i++) {
            sum+=arr[i].getMark();
        }
        avg=sum/arr.length;
        
        return avg;
    }
    
    public static int pass(Student[]arr) {
        for(int i=0;i<arr.length;i++) {
            if(arr[i].mark>=50) {
                count++;
            }
        }
        return count;
    }
    public static int fail(Student[]arr) {
        for(int i=0;i<arr.length;i++) {
            if(arr[i].mark<50) {
                count1++;
            }
        }
        return count1;
    }
}
public class Student {
    public int id; //Declaration of the three variables
    public String name;
    public int mark;
    
    int getId() { //mini methods that return the variables so that they can be used in a separate class, or main method.
        return id;
    }
    String getName() {
        return name;
    }
    int getMark() {
        return mark;
    }

}
aviv-1
  • 1

1 Answers1

0

You need to override the "toString()" method in the Student Class.

Add the following snippet to the Student class

@Override
public String toString() {
    return "Student{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", mark=" + mark +
            '}';
}

When you call Arrays.toString(arr), it would invoke the toString() method for all the Student objects stored in the array. The default toString() method returns the hashcode of the called object therefore you must override it with the above code snippet

Dulshan
  • 31
  • 7