Reputation: 1
I have 2 classes, NonEmptyTree and EmptyTree that implement the Tree interface. toString()
method in NonEmptyTree class should return a string: key=>value key=>value key>value
etc...
I do not know how to remove last space at end of result.
EDIT: I cannot use any methods in the String class, and I cannot compare anything to null.
public String toString() {
String result = "";
result+=(this.left.toString());
result+=this.key;
result+="=>";
result+=this.value;
result+=" ";
result+=this.right.toString();
return result;
}
I've tried having a variable for the class that indicates if a NonEmptyTree instance is the largest in the current tree, but console displayed same string.
for example, the string would look like this:
"7=>seven 10=>ten 12=>twelve 15=>fifteen 16=>sixteen 17=>seventeen 20=>twenty 30=>thirty "
any help would be appreciated. thanks
Upvotes: 0
Views: 2827
Reputation: 3736
Can you simply add an 'if'? See below:
public String toString()
{
String result = "";
result+=(this.left.toString());
result+=this.key; result+="=>";
result+=this.value;
if (this.right!=null) // Just add this, so it doesn't add an extra space if no right result exists
{
result+=" ";
result+=this.right.toString();
}
return result;
}
Upvotes: 1
Reputation: 76898
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.left.toString());
result.append(this.key);
result.append("=>");
result.append(this.value);
result.append(" ");
result.append(this.right.toString());
return result.toString().trim();
}
Upvotes: 2
Reputation: 16226
Use String.trim()
:
return result.trim()
BTW. if you do a lot of String
additions it's better to use StringBuilder
and its method append()
instead of adding multiple String
s with +
.
Upvotes: 2