1

I am working on a project from a Java text book, and I have come across an issue. I am attempting to print the variables in an array, however it continually prints the variables location (@hex code) instead of the actual variable... I believe I am attempting to print the array correctly via using a 'for loop'. I have attached my code below...

import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;

public class Main
{
    public static void main(String[] args)
    {
        int ARRAY_LENGTH = 2;

        Scanner in = new Scanner(System.in);
        Person[] Persons;

        Persons = new Person[ARRAY_LENGTH];

        for (int i = 0; i < ARRAY_LENGTH; i++)
        {
            System.out.println("Enter a name to add to the array: ");
            Persons[i] = new Person(in.next());
        }

        //Arrays.sort(Persons);

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

&

public class Person implements Comparable<Person>
{
    private String name;

    public Person (String aName)
    {
        String name = aName;
    }

    public String getName()
    {
        return name;
    }

    public int compareTo(Person o)
    {
        Person other = (Person) o;
        if (this.name.equals(o.name))
        {
            return 0;
        }
        if (this.name.compareTo(o.name) < 0)
        {
            return -1;
        }
        return 1;
    }
}

Any and all guidance is appreciated. Thank You!

Caleb
  • 27
  • 3

1 Answers1

5

You need to override the toString method in your Person class.

public class Person implements Comparable<Person>
{
    private String name;

    public Person (String aName) { ... }

    public String getName() { ... }

    public int compareTo(Person o) { ... }

    @Override
    public String toString() {
        return "My name is " + name; // For the example, you could return any String you want
    }
}

the toString method is generally used to provide a description of the object.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67