把我的堆栈变成一个字符串?

时间:2013-06-24 02:31:04

标签: java string stack

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;

这有助于解决我的问题;感谢

2 个答案:

答案 0 :(得分:0)

使用StringBuilder处理toString创建。您可以使用的模板是

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

答案 1 :(得分:0)

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

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;