[英]new class with method toString()
This is related to an earlier question I asked. 这与我之前提出的问题有关。 I'm adding a toString() method to a class. 我在类中添加了toString()方法。 The class creates an arbitrarily long natural number using a stack of integer. 该类使用整数堆栈创建任意长的自然数。 I'm only incrementing and decrementing, so stack seemed a good way to go. 我只是增加和减少,所以堆栈似乎是个不错的选择。 Anyway, I don't get any output from the following code: 无论如何,我从以下代码中没有得到任何输出:
public String toString() {
String out_final = "", backwards = "", temp_str = "";
Integer temp_int = 0;
Character temp_char = ' ';
while(!number.empty()) {
temp_int = number.pop();
temp_str = temp_int.toString();
backwards.concat(temp_str);
}
while(backwards.length() > 0) {
temp_char = backwards.charAt(backwards.length() - 1);
temp_str = temp_char.toString();
out_final.concat(temp_str);
}
return out_final;
}
It is invoked by System.out.println(b4.toString());
它由System.out.println(b4.toString());
调用System.out.println(b4.toString());
The object number
refers to my Stack<Integer>
I've gotta take from the end of the stack (obviously in reverse) and then reverse it again to print correctly. 对象number
指的是我必须从堆栈末尾取走的Stack<Integer>
(显然是反向的),然后再次反转以正确打印。 Anyway, no hurry on this one, but help is always appreciated! 无论如何,不要着急这一点,但总是能得到帮助!
Strings are immutable: 字符串是不可变的:
backwards.concat(temp_str);
should be 应该
backwards = backwards.concat(temp_str);
And the same with the out_final concatenation. 与out_final串联相同。
Alternatively, if your stack is fairly large, a StringBuilder may be useful and possibly more efficient to you. 或者,如果您的堆栈相当大,则StringBuilder可能对您有用并且可能更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.