创建类对象来进行阶乘递归? [英] Creating class object to do factorial recursion?
本文介绍了创建类对象来进行阶乘递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被分配了一个使用递归来编写程序的问题,这是正常工作的,我唯一的问题是它被指定创建一个类对象来进行因子计算而不是方法...我这样做了吗?
I was assigned a problem to write a program using recursion, which is working properly, my only question is that it was specified to create a class object to do the factorial calculation instead of method...am I doing this right?
import java.util.*;
import java.io.*;
public class Assignment2A {
public static void main(String[] args){
Scanner scan = new Scanner(System.in); //sets up scanner
boolean correct = true; //sets up boolean operation
while(true){
try{ //try catch operation
System.out.println("Welcome to the factorial function");
System.out.println("Please enter a number or press 0 to exit");
long startTime =System.nanoTime();
System.out.println("Start Time: "+startTime+" nanoseconds."); //display the start time
int n = scan.nextInt(); //scans the input
int factorial= fact(n);
System.out.println("The Factorial of the number entered is: " + factorial);
long taskTime = System.nanoTime() - startTime;
System.out.println("Task Time: "+taskTime+" nanoseconds.\n\n");
}catch(Exception e){ //checks if the input is a string or character
System.out.println("That is not a number!"); //displays that the input is invalid
long startTime =System.nanoTime();
long taskTime = System.nanoTime() - startTime;
System.out.println("Task Time: "+taskTime+" nanoseconds.");
System.exit(0); //exits the program
}
}
}
static int fact(int n){
int output; //sets the output as int
long startTime = System.nanoTime(); //gets the start time of the cpu
long taskTime = System.nanoTime()-startTime; //gets the task time
if (n==0){ //if the input is 0, system exits
System.out.println("Exiting Program");
System.out.println("Task Time: "+taskTime+ " nanoseconds."); //displays cpu time
System.exit(0);
}
else if(n==1){
return 1; //if input is 1, the factorial of 1 is 1
}
output = fact(n-1)*n; //recursive method for factorial
return output;
}
}
推荐答案
否,你创建了一个计算阶乘的方法,事实(int n)。
No, you created a method, fact(int n) that calculates the factorial.
你应该用一个计算阶乘的方法创建一个新类。将实例化该类的对象,然后,将从类对象调用计算阶乘的方法。
You should create a new class with a method that calculates the factorial. An object of the class would be instantiated and then, the method that calculates the factorial would be invoked from the class object.
示例:
// outside the while loop instantiate your class object for
// dealing with factorial computations
Factorial factorial = new Factorial();
// inside the while loop, instantiate your method for
// computing factorial of "n", invoking your factorial
// computation method that is defined inside your class
int result = factorial.computeFactorial(n);
这篇关于创建类对象来进行阶乘递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文