SeanConnery
SeanConnery

Reputation: 67

Multiple strings at one index of an array list

I have a constructor here with two strings:

public class person
{
    String first;
    String last;
    public person (String first, String last)
    {
        this.first = first;
        this.last = last;
    }
    public String toString()
    {
        String result = first + "\n";
        result += last + "\n";

        return result;
    }
}

And a main method that creates two objects of the constructor:

import java.util.ArrayList;
public class k
{
    public static void main (String[] args)
    {
        ArrayList<person> list = new ArrayList<person>();
        person ken = new person ("Ken", "Smith");
        person ben = new person ("Ben", "Smith");

        list.add (ken);
        list.add (ben);

        System.out.println (list.get(0));
    }
}

Right now the code prints Ken Smith. My question is: How would I get it to print just Ken instead of Ken Smith?

Upvotes: 2

Views: 1431

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201429

By convention, Java class names start with a capital letter. Next, you override toString() to print both names. For just the first name, you'd add a getter (and for this example, I added a getter for the last name as well)

public class Person {
    String first;
    String last;

    public Person(String first, String last) {
        this.first = first;
        this.last = last;
    }

    public String getFirst() {
        return first;
    }

    public String getLast() {
        return last;
    }

    public String toString() {
        String result = first + "\n";
        result += last + "\n";

        return result;
    }
}

Then you could call (in main) with something like

System.out.println (list.get(0).getFirst());

Upvotes: 6

Related Questions