Reputation: 45
I'm relatively new to programming and can't sort this one out. I have an array stack that I have just set up. I'm trying to create a toString() method that returns the contents of the array listed from top to bottom of the stack.
For example, the array contains elements...[1,2,3,4,5] with '5' being the top of the stack and '1' being the bottom. I want to return '5', followed by a new line, then '4', etc. until I reach '1.'
The code I have so far for the toString method is:
/**
* Returns a string representation of this stack. The string has
* form of each element printed on its own line, with the top most
* element displayed first, and the bottom most element displayed
* last.
* If the list is empty, returns the word "empty".
* @return a string representation of the stack
*/
public String toString()
{
String result = "";
for (int scan = 0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
Currently, this is returning the contents of the stack from bottom to top, not top to bottom. Any suggestions?
Upvotes: 1
Views: 2462
Reputation: 1323
Try this:
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i=stack.size()-1;i>=0;i--) {
sb.append(stack.get(i)).append("\n");
}
return sb.length()>0 ? sb.toString(): "empty";
}
Upvotes: 0
Reputation: 1
According to the specification's comment, the code should verify if the array is empty:
public String toString(){
String result = "";
for (int scan =stack.length-1 ; scan >= 0; scan--) {
if(stack[scan] != null ) {
result = result + stack[scan].toString() + "\n";
}
}
if( result.length() == 0) {
return "empty";
} else {
return result;
}
}
Upvotes: 0
Reputation: 604
replace your toString method with :
public String toString(){
String result = "";
for (int scan =top-1 ; scan >= 0; scan--)
result = result + stack[scan].toString() + "\n";
return result;
}
Upvotes: 2