【问题标题】:Error in code to find the factorial of a number entered by a user查找用户输入数字的阶乘的代码错误
【发布时间】:2021-01-14 22:07:59
【问题描述】:
public static int Factorial(int num) {
    int factorial = 1;
    int num = Integer.parseInt(txtFactorial.getText());

    for (int i = 1; i <= num; i++) {
        factorial = factorial * 1;
    }

    return factorial;
}

上面的代码是我试图放入子程序的代码,以查找用户输入的数字的阶乘并将其显示在JLabel 中。问题是它显示了int num = Integer.parseInt(txtFactorial.getText()); 代码的错误。这段代码获取用户的输入并将其存储到变量 num 中,以便以后用于查找阶乘。

【问题讨论】:

    标签: java loops for-loop factorial


    【解决方案1】:

    你应该改变你的计算。

    public static int Factorial(int num)
    {
        int factorial = 1;
        // delete this line int num = Integer.parseInt(txtFactorial.getText());    
        for (int i = 1; i<=num; i++)
        {
            factorial = factorial * i;
        }    
        return factorial;
    }
    

    并像这样使用函数:

    ResultLabel.setText(string.valueOf(Factorial(Integer.parseInt(txtFactorial.getText()))));

    【讨论】:

      【解决方案2】:

      范围内已定义变量“num”

      int num2 = Integer.parseInt(txtFactorial.getText());
      

      上面写f你要一个新变量

      num = Integer.parseInt(txtFactorial.getText());
      

      如果要更改现有变量 num 的值,请编写上述内容。

      【讨论】:

        【解决方案3】:

        正整数的阶乘 n - 是小于或等于 n 的所有正整数的乘积。 0 的阶乘是 1

        public static void main(String[] args) {
            System.out.println(factorial(3));   // 6
            System.out.println(factorial(0));   // 1
            System.out.println(factorial(-10)); // 1
        }
        
        public static int factorial(int num) {
            // factorial of a positive integer, or 1 otherwise
            int factorial = 1;
            for (int i = 1; i <= num; i++) {
                // sequential multiplication
                // of numbers in the loop
                factorial = factorial * i;
            }
            return factorial;
        }
        

        使用 streams,您的代码可能如下所示:

        public static int factorial(int num) {
            // factorial of a positive integer, or 1 otherwise
            return IntStream.rangeClosed(1, num)
                    // sequential multiplication
                    // of numbers in the stream
                    .reduce((a, b) -> a * b)
                    .orElse(1);
        }
        

        【讨论】:

          【解决方案4】:

          变量num有重复,你需要为这个局部变量使用另一个值:

          int num = Integer.parseInt(txtFactorial.getText());
          

          改用这个:

          int parsedNum = Integer.parseInt(txtFactorial.getText());
          

          如果您更改局部变量的名称,那么它应该可以工作。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-01-25
            • 1970-01-01
            • 2019-10-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-28
            相关资源
            最近更新 更多