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

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

4

2 回答 2

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();
}
于 2013-06-24T03:00:54.003 回答
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;
于 2013-06-24T03:03:12.987 回答