简体   繁体   English

返回供语句打印的值

[英]Returning the value that for statement prints

I would like to return all the information as output that the for statement prints. 我想返回所有信息作为for语句打印的输出。

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. 使用StringBuilder累积结果。 Update: Then convert it to int using Integer.parseInt : 更新:然后使用Integer.parseInt将其转换为int:

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. 请注意,这仅适用于相当小的i值(最大为9),否则您将得到整数溢出。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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