简体   繁体   中英

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?

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

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