开发者

new class with method toString()

This is related to an earlier question I asked. I'm adding a toString() method to a class. 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()); The object number refers to my Stack<Integer> I've gotta take from the end of the stack (obviou开发者_开发知识库sly in reverse) and then reverse it again to print correctly. 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.

Alternatively, if your stack is fairly large, a StringBuilder may be useful and possibly more efficient to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜