开发者

Returning the value that for statement prints

开发者 https://www.devze.com 2023-02-08 10:48 出处:网络
I would like to return all the information as output that the for statement prints. For instance: public static int countNumbers(int x) {

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 some开发者_开发百科where else, I will get the output.

So:

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

How can this be done?


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.


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;

}


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;
}
0

精彩评论

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

关注公众号