Java 把我的堆栈变成字符串?

Java 把我的堆栈变成字符串?,java,string,stack,Java,String,Stack,这解决了我的问题;感谢使用StringBuilder来处理toString创建。您可以使用的模板是 String message = ""; //a string to store the whole message for (int c = stack.length - 1; c >= 0; c--) { message += ", "+stack[c]; //add the next element to the message } message = message.substri

这解决了我的问题;感谢使用StringBuilder来处理toString创建。您可以使用的模板是

String message = ""; //a string to store the whole message
for (int c = stack.length - 1; c >= 0; c--) {
message += ", "+stack[c];  //add the next element to the message
}
message = message.substring(2); //cut off the first ", "
return message;

在循环中调用return将立即退出循环。您需要做的是这样的事情:

public String toString(){
    StringBuilder output = new StringBuilder();
    output.append(this.getClass().getName());
    output.append("[");
    // append fields

    // to append the Stack you could use Arrays.toString
    // or just iterate as you are trying to do
    int i=top;

    do {
        T result = stack[top-i];
        i--;
        output.append(result != null?result.toString():"null");
    } while (i>=0);

    output.append("]");
    return output.toString();
}

toString方法将只返回堆栈中的顶部项;循环不会像我需要的那样在整个堆栈中运行。您可以将每个元素从堆栈中弹出并调用string。阅读更多有关输入的信息
String message = ""; //a string to store the whole message
for (int c = stack.length - 1; c >= 0; c--) {
  message += ", "+stack[c];  //add the next element to the message
}
message = message.substring(2); //cut off the first ", "
return message;