使用 java 中的可调用接口查找阶乘

Finding the factorial using callable interface in java

package projsamples;

import java.util.Collection;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FactorialUsingThreads {

    public static void main(String[] args)  throws InterruptedException,ExecutionException{

        Scanner reader = new Scanner(System.in);
        int number = reader.nextInt();
        ExecutorService es = Executors.newSingleThreadExecutor();
        Future<Integer> result=es.submit(new FactorialCalc(number));
        System.out.println("result value after calc is: "+ result);
        int finalResult =(int)result.get();
        System.out.println("The result of the factorial calculation for the"+number+"is: "+finalResult);
    }

    }

    class FactorialCalc implements Callable<Integer>{

    private int number;

    public FactorialCalc(int number) {
        super();
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        // TODO Auto-generated method stub
        return factorial(number);
    }

    private Integer factorial(int number2) throws InterruptedException  {
        // TODO Auto-generated method stub
        int number = number2;
        int result = 1;
        while(number2 !=0){

            result = number*result;
            number=number-1;
            Thread.sleep(100);

        }
        System.out.println("result"+result);
        return result;

    }
}

在上面的代码中,我想做的是,我想找到用户输入的任何数字的阶乘数。 返回的结果是当我尝试对整数对象进行类型转换并且获取值没有发生时的对象。我知道这可能是一件非常基本的事情,我无法 do.any 对此有所帮助。

非常感谢所有能提供帮助的好心人。

这与多线程有关。你只需要在 factorial 方法中使用 number2,并记住将其递减。

private Integer factorial(int number2) throws InterruptedException  {    
    int result = 1;
    while(number2 != 0){    
        result = number2 * result;
        number2 = number2 - 1;
        Thread.sleep(100);    
    }
    System.out.println("result"+result);
    return result;    
}