1

I have a program class and a student class, the student constructor creates a student and stores it in the array, the problem is when I try to print the array I get the following printed out:

metClassTwo.Student@5c74c3aa

How can I get the program to print the array details correctly?

print method:

  public static void listStudent() {
    for (int i = 0;i < myClassCount;i++) {
      if (myClass[i] != null) {
        System.out.println(myClass[i]);
      }
    }
  }

myClassCount is incremented by one each time a student is added.

Array:

  static final Student[] myClass = new Student[6];
Colin747
  • 4,955
  • 18
  • 70
  • 118

6 Answers6

2

implement toString() method for Student class. for example:

public String toString() {
    return this.name+" "+this.surname;
}
itasyurt
  • 76
  • 4
1
class Student {
  String name;
  @Override
  public String toString(){ return name;}
}

myClassCount is not guaranteed the index bounds, use array length to check the bounds of the array.

for (int i = 0; i < myClass.length; i++) {
  if (myClass[i] != null) {
    System.out.println(myClass[i]);
  } 
}  

or better use foreach loop

for (Student s : myClass) {
  if (s != null) {
    System.out.println(s);
  } 
}  
1

You have to override the toString() method on your Student class. Java doesn't know what output you expected when you say "print the Student object", so it just inherits the toString() method from the Object class which is just the class's name and the current instance's hash code.

Try something like this (and use whatever variables on the student object you want to have printed.

class Student {
   public String toString() {
       return String.format("%s, %s\n", this.studentName, this.studentAge);
   }
   ...
}
kba
  • 19,333
  • 5
  • 62
  • 89
0

You need to override your Student class toString() method:

@Override 
public String toString() {
  return this.getFirstName() + " " + this.getLastName();
}

I have no idea what your Student class looks like but this should give you a general idea. In case you cannot modify the Student class you can do the same thing in the println method:

 for (int i = 0;i < myClassCount;i++) {
      if (myClass[i] != null) {
        System.out.println(myClass[i].getFirstName() + " etc...");
      }
}
dimoniy
  • 5,820
  • 2
  • 24
  • 22
0

The method Arrays.toString will print out all the elements of your Array nicely.

You also need to implement the toString method of your student object so the student itself will display nicely.

Most IDEs have utilities to automatically generate toString methods. For Netbeans look under the source menu -> generate -> toString.

Tim B
  • 40,716
  • 16
  • 83
  • 128
-1

You have to override the toString method in the Students class.

e.g.:

@Override 
public String toString() {

StringBuilder result = new StringBuilder();

result.append(something);
.....
return result.toString();
}
Ben
  • 1,157
  • 6
  • 11