我想返回所有信息作为 for 语句打印的输出。
例如:
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.
}
所以当我在其他地方调用该方法时,我会得到输出。
所以:
int output = countNumbers(3);
//output = 123;
如何做到这一点?
最佳答案
使用StringBuilder
来累积结果。 更新:然后使用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());
}
请注意,这仅适用于相当小的 i
值(最多 9),否则您将遇到整数溢出。
关于java - 返回 for 语句打印的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904090/