static、this、包--求n的阶乘

一、程序题目

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

二、运行结果

三、代码分析

1.Computer

package www;

public class Computer {                //创建Computer类
    
    public static int jiecheng(int n){           //创建jiecheng方法
        int result=1;                             //求阶乘的运算
        for(int i=1;i<=n;i++){
            result*=i;
        }
        
        return result;
    }

}

2.App

package com;

import java.util.Scanner;

import www.Computer;                             //引入www包下的Computer类
public class App {

    public static void main(String[] args) {
        Scanner reader=new Scanner(System.in);  //创建Scanner对象
        System.out.println("输入");
        Computer c=new Computer();               //创建对象
        int a=reader.nextInt();                   //从键盘输入
        
        
        System.out.println(a+"的阶乘为:"+c.jiecheng(a));     //输出:调用成员变量c下方法
    }

}

猜你喜欢

转载自www.cnblogs.com/wanghainan/p/11541560.html