简体   繁体   English

在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;

    }
}

In the above code what I am trying to do is, I want to find the factorial number for any number entered by user.在上面的代码中,我想要做的是,我想找到用户输入的任何数字的阶乘数。 The result returned is the object when I try to typecast the integer object and the get the value is not happening.返回的结果是当我尝试对整数对象进行类型转换时的对象,并且没有发生获取值。 I know this could be a very basic thing which I am not able to do.any small heads up on this would be helpful.我知道这可能是我无法做到的非常基本的事情。对此的任何小提示都会有所帮助。

Thanks a lot in advance for all the kind people who can help.非常感谢所有可以提供帮助的好心人。

This has to do with multithreading.这与多线程有关。 You just need number2 in factorial method, and remember decrement it.您只需要在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;    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM