2

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?

1 Answer 1

6

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());
Sign up to request clarification or add additional context in comments.

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.