java - 结果没有初始化?

标签 java loops for-loop methods return

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/

相关文章:

javascript - 有没有办法让代码更简单、更高效?

java - Arrays.getOnlyElement()?

java - Salesforce SOAP 连接命名空间问题

java - 如何从 Java 代码启动 Apache Storm UI?

perl - 在 perl 中搜索多个术语

java - Java 新手,学习很快,但不明白为什么我的 for 循环不会打印

java - 将 SOAP 响应转换为 xstream 对象

java - 如何从数字数组中找出方差?

python - 一行 for 循环将元素添加到 Python 中的列表

c++ - 无限for循环?