Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java数组堆栈,从上到下打印堆栈内容_Java_Arrays_Stack - Fatal编程技术网

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

Java数组堆栈,从上到下打印堆栈内容,java,arrays,stack,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 o

我对编程比较陌生,不能把这件事理清。我刚刚设置了一个数组堆栈。我试图创建一个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;
}
/**
*返回此堆栈的字符串表示形式。绳子已经断了
*每个元素的形式打印在自己的行上,最上面的
*首先显示元素,然后显示最底部的元素
*最后。
*如果列表为空,则返回单词“empty”。
*@返回堆栈的字符串表示形式
*/
公共字符串toString()
{
字符串结果=”;
用于(int scan=0;scan

目前,这是从下到上而不是从上到下返回堆栈的内容。有什么建议吗?

将您的toString方法替换为:

 public String toString(){
     String result = "";
     for (int scan =top-1 ; scan >= 0; scan--)
         result = result + stack[scan].toString() + "\n";
     return result;
 }

根据规范的注释,代码应验证数组是否为空:

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;
    }

}
试试这个:

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";  
}

对代码最细微的更改是
result=stack[scan].toString()+“\n”+result
-预先添加新数据,而不是追加它。另外,请注意
.toString()
是多余的(除非您确实希望在
堆栈[scan]
null
的事件中抛出
NullPointerException
,而不是在字符串中显示为
null
)。您应该使用
StringBuilder
,而不是直接串接。