我对编程比较陌生,无法解决这个问题。我有一个刚刚设置的数组堆栈。我正在尝试创建一个 toString() 方法,该方法返回从堆栈顶部到底部列出的数组的内容。
例如,数组包含元素...[1,2,3,4,5],其中“5”是堆栈顶部,“1”是底部。我想返回“5”,然后是一个新行,然后是“4”,依此类推,直到到达“1”。
到目前为止,我的 toString 方法的代码是:
/**
* 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;
}
目前,这是从下到上返回堆栈的内容,而不是从上到下。有什么建议吗?
最佳答案
将 toString 方法替换为:
public String toString(){
String result = "";
for (int scan =top-1 ; scan >= 0; scan--)
result = result + stack[scan].toString() + "\n";
return result;
}
关于Java数组栈,从上到下打印栈内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682178/