一、题目一:
1、需求分析:
编写一个类Computer,类中含有一个求n的阶乘的方法。将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参数决定),并将结果输出。
2、设计实现:
Computer类:定义了一个公开的Computer类、一个公开的int型的静态方法、两个int型变量
代码:
package one;
public class Computer {
long t = 1;
public long factorial(int n)
{
for (int i = 1; i <= n; i++) {
t *= i;
}
return t;
}
}
import one.*;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Computer computer=new Computer();
Scanner sc =new Scanner(System.in);
System.out.println("请输入要计算阶乘的n值:");
int n=sc.nextInt();
long value=computer.factorial(n);
System.out.println(n+"的阶乘为:"+value);
}
}