static,包,this--求阶乘

一、题目

编写一个类Computer,类中含有一个求n的阶乘的方法。将该类打包,并在另一包中德Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参数决定),并将结果输出。

二、代码

//Computer类
package com;

public class Computer {
    int n;
    static int num=1;//定义初值
    public int jiecheng(int aa){
    for(int i=1;i<=aa;i++){//循环求阶乘
        num*=i;
    }
    return num;
    }
}
//App
package cn;
import java.util.Scanner;
import com.Computer;
public class App {
    public static void main(String[] args) {
        System.out.println("输入一个数");
        Computer com=new Computer();//创建com对象
        Scanner reader=new Scanner(System.in);
        int aa=reader.nextInt();//接受键盘输入
        System.out.println("阶乘为:"+com.jiecheng(aa));//调用com中的jiecheng()的返回值
    }

}

三、运行结果

猜你喜欢

转载自www.cnblogs.com/leeyangtongxue/p/11541493.html