简体   繁体   中英

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 (obviously 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM