这里是我的代码:如何从for循环中返回一个值?
import java.util.*;
public class factorialdisplay {
// Main Method. Prints out results of methods below.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + factorial(n));
}
}
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
return f;
}
return f;
}
}
我想要得到的输出:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
但是当我运行的代码,我得到这个:
0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1
我的问题是,我如何将for
循环的每次迭代的结果通过factorial
静态方法返回到main
方法?
你真的想在这种情况下返回吗? –
一个方法返回一次。 –
从'for'循环中删除'return'语句。只是从'2'迭代到'n'并计算'factorial'并且一次迭代,简单地返回'factorial' :-)为什么要做额外的乘法,任何乘以1的值总是相同的值! –