import java.util.*;
//Creates a program which allows the user to find the factorial of a number
public class forLoop {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want the factorial from: ");
int number = input.nextInt(); // user input
input.close();
int result_2 = getFactorial(number); //initializes getFactorial method
System.out.println("The factorial of " + number + " is " + result); //prints results
}
public static int getFactorial (int num1) {
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
return result; // returns results (here is the problem)
}
}
最佳答案
编译器不能假定循环至少执行一次——这是 result
的必要条件得到分配。
更改声明result
解决问题的方法如下:
int result = 1;
这将有助于您的代码编译,但它不会修复计算阶乘时的逻辑错误:目前,由于错误的循环条件,您的循环将无限期地运行。
您应该将 1
中的数字相乘至 num1
, 包括的。改变循环条件 times >= 1
而不是 times <= 1
, 和循环体到 result *= times
修复此错误。
关于java - 结果没有初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618019/