0

I have a State class with these fields

String name;
City capital;
ArrayList<String> neighbors;

I have a toString() method

public String toString(){
    return ("new State(" + 
        this.name  + ", " + 
        this.capital + ", " + 
        this.neighbors + ")\n");
}

I am trying to test this method on the state

State ME = new State("ME", augusta, MEneighbors );

Where augusta is a defined City, and MEneighbors is an ArrayList with

MEneighbors.add("NH");

This is my test so far

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + [NH] + ")");

I don't quite understand why this isn't working. It works until the ArrayList MEneighbors. How can I get it to add the ArrayList as a String?

Many thanks.

5
  • 1
    Does this even compile? Commented Nov 15, 2013 at 22:47
  • How is it not working? Are you getting incorrect output? An exception message? Commented Nov 15, 2013 at 22:47
  • 1
    + [NH] + This will never compile in this world. Commented Nov 15, 2013 at 22:48
  • is ArrayList's default .toString() not sufficient? Commented Nov 15, 2013 at 22:48
  • 1
    + [NH] + doesn't compile, what are you trying to do Commented Nov 15, 2013 at 22:48

2 Answers 2

2

Even if you fix the code to be:

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + "[NH]" + ")");

Note: quotes around brackets.

You still forget to add the "\n" in the right side! Because your toString method adds "\n" in the end!

Sign up to request clarification or add additional context in comments.

Comments

0

When you define the toString method, call the toString method for ArrayList, like this

public String toString(){
return ("new State(" + 
    this.name  + ", " + 
    this.capital + ", " + 
    this.neighbors.toString() + ")\n");
}

the toString method

Returns a string representation of this collection. The string representation consists of 
a list of the collection's elements in the order they are returned by its iterator, 
enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", "
(comma and space). Elements are converted to strings as by String.valueOf(Object).

Comments