Dave
Dave

Reputation: 45

Returning the value that for statement prints

I would like to return all the information as output that the for statement prints.

For instance:

public static int countNumbers(int x) {

    for (int i = 1; i <= x; i++) {
        System.out.println(i);
    }

    return SOMETHING; // This something should be the values for statements prints.
                      // For example, countNumbers(5) returns 12345.
}

So when I call the method somewhere else, I will get the output.

So:

int output = countNumbers(3);
//output = 123;

How can this be done?

Upvotes: 0

Views: 77

Answers (3)

Patrick
Patrick

Reputation: 11

How about this:

public static int countNumbers(int x) {
    int result = 0;
    for (int i = 1; i <= x; i++) {
        result *= 10;
        result += i;
    }
    return result;
}

Upvotes: 1

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

How about this:

public static int countNumbers(int x) {

    int retVal = 0;

    for (int i = 1; i <= x; i++) {
        System.out.println(i);
        retVal += i * Math.pow(10, x - i); // Is it math? I'm a C++ programmer
    }

    return retVal;

}

Upvotes: 1

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

Use a StringBuilder to accumulate the result. Update: Then convert it to int using Integer.parseInt:

public static int countNumbers(int i) {
    StringBuilder buf = new StringBuilder();

    for (int i=1; i<=5; i++) {
      buf.append(i);
    }
    return Integer.parseInt(buf.toString());
}

Note that this works only for fairly small values of i (up to 9), otherwise you will get an integer overflow.

Upvotes: 5

Related Questions