V1rtua1An0ma1y
V1rtua1An0ma1y

Reputation: 627

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!

Upvotes: 0

Views: 175

Answers (1)

jerluc
jerluc

Reputation: 4316

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.

Upvotes: 7

Related Questions