0

there I have a question. I am trying hard to do this without asking but after a couple of hours of searching and trying, I cannot seem to make it work. This is for an assignement. I just need guidance.

I have to create the following objects

Student(String name, double GPA)
Classroom (int maxClassSize)

The classroom object initializes an arrray where I would store the Student objects.

However, the array in Classroom() is declared as private (private Student students[]) so I am adding students using a public method

public boolean add(Student aStudent)  *do not worry about the boolean type

I can also return the value of an array using a get method

public Student getStudent(int position)

Those methods are set in the assignment.

My question is, when I try to output the objects in the array (again, this is required for the assignment). I get the reference, ie Student@23e45e23 instead of the name and GPA of each object.

I cannot use toString.

Any ideas?

3
  • You have to implement a toString method for Student, otherwise, it gives you a default one(the memoery address). Commented Feb 13, 2014 at 4:46
  • if you can access the student's properties you can do println getStudent(0).getName() + getStudent.getGPA(); Commented Feb 13, 2014 at 4:47
  • I asked the teacher and I cannot use toString, and the assignment did specifically say "The proof output must be from objects returned to your main method by the classroom object." (his words). Commented Feb 13, 2014 at 4:52

3 Answers 3

3

You are seeing the (non-human friendly) output of the toString() method of the Object class.

Define a toString() method in your Student class, which will override the implementation found in the Object class (which Student implicitly extends)

Something like:

@Override
public String toString() {
    return firstName + " " + lastName + " - " gpa;
}

The toString() method is called whenever you print an object:

System.out.println(student);

if student is not null, this has the same effect as calling:

System.out.println(student.toString());
Sign up to request clarification or add additional context in comments.

Comments

0

Try to override toStringMethod()

Method1:

class Studet{
//
//
//
public String toString(){
 return name+""+GPA;
}

Method2:

make object of Class

and then access the values of variables using that object.

Comments

0

I was able to resolve it finally without using toString (can't use it) with

(student1.getName(classroom.getStudent(0))

and

(student1.getGPA(classroom.getStudent(0))

Thanks everyone!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.