Java数组栈,从上到下打印栈内容

标签 java arrays stack

我对编程比较陌生,无法解决这个问题。我有一个刚刚设置的数组堆栈。我正在尝试创建一个 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/

相关文章:

java - 如何从数组中删除空字符串

c - 存储字符串的某些部分

c - K&R 波兰语计算器中可能存在的错误

android - 如何正确删除所有 Activity 堆栈?

javascript - 我想从数组中返回一个 JSON 对象

java - 省略号禁用初始文本

java - 使用 setText 和 onClickListener 将数据从 EditText 传输到另一个 Activity 的 TextView?

java - Spring Boot 中的自定义 JWE 过滤器阻止 CORS 选项请求

java - 从用户输入读取堆栈的整数

java - 使用 JavaOSC 向 Android 发送/接收 OSC 消息