0

This code is to get the firstName, LastName, and StudentID by reading it from a file and displaying the information in the main file. When I run my program, instead of printing the information of the students, it prints out a chain of characters and numbers.

public class main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Student[] students = new Student[10];
        getStudentData(students);

        for (int i = 0; i < students.length; i++){
            System.out.println(students[i]);
        }
    }


    public static void getStudentData(Student[] students){
        String infileName = "studentlist.txt";
        Scanner reader = null;
        try {
            reader = new Scanner (new File(infileName));
            int index = 0;
            while(reader.hasNext()){
                String oneLine = reader.nextLine();
                String[] parts = oneLine.split(" ");
                long studentID = Long.parseLong(parts[2]);
                students[index] = new Student(parts[0],parts[1],studentID);
                index++;
            }
        } catch (FileNotFoundException err) {
            System.out.println(err);
        } finally {
            if (reader != null)
                reader.close();
        }
    }
}
Mushroomator
  • 6,516
  • 1
  • 10
  • 27
Adrian
  • 1
  • 2
  • Please provide the content of your `studentlist.txt` file (or at least a few lines). – Mushroomator Mar 22 '22 at 13:11
  • Have you defined a `toString()` method on your `Student` class? You need to do this otherwise the default `toString()` implementation of class `Object` will be used. – Mushroomator Mar 22 '22 at 13:16
  • Thank you so much, yeap I make a mistake for not defining a toString() method in my Student Class. – Adrian Mar 22 '22 at 13:20

1 Answers1

0

Have you defined a toString() method on your Student class? You need to do this otherwise the default toString() implementation of the superclass for all classes (class Object) will be used which returns the name of the class concatenated with @ and the hashcode of the class in hexadecimal format.

Add this method to your Student class and return a meaningful String containing the attribute values of a Student object instead of my descriptive String.

@Override
public String toString() {
    return "return a string here that represents the student and his/ her attribute values";
}

FYI: Many IDEs can generate an arbitrary toString() method for you.

See the this thread for more details on Object::toString().

Mushroomator
  • 6,516
  • 1
  • 10
  • 27