第6次作业--static关键字、对象

题目一:编写一个类Computer,类中含有一个求n的阶乘的方法。将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n

的阶乘的方法(n值由参数决定),并将结果输出。

Computer类:

package lph;

public class Computer {
    int a=1; 
    public int getA(int x) {
        for(int i=1;i<x+1;i++) {
            a=a*i;    
        }
        return a;
    }
}

App类

package LLL;
import java.util.*;
import lph.Computer;
public class App {
    public static void main(String args[]){
    System.out.println("请输入一个数字");
    Computer b=new Computer();
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    System.out.println("阶乘为:"+b.getA(n));
    }
}

运行结果:

 

题目二:

设计一个MyPoint类,表示一个具有x坐标和y坐标的点,该类包括:

  • 两个私有成员变量x和y表示坐标值
  • 成员变量x和y的访问器和修改器
  • 无参构造方法创建点(0,0)
  • 一个有参构造方法,根据参数指定坐标创建一个点
  • distance方法(static修饰)返回参数为MyPoint类型的两个点对象之间的距离

    编写主类Test,在主类中输入两个点坐标,创建两个点对象,利用distance()方法计算这两个点之间的距离

package Distance;
public class Distance {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyPoint p1=new MyPoint(5,3);
        MyPoint p2=new MyPoint(3,6);//创建P1 P2 对象
        double distance=MyPoint.getdistance(p1, p2);
        System.out.println("两点之间距离为:"+distance);
    }

}
class MyPoint{
    double x;
    double y;//建立坐标x和y
    public MyPoint(){//对坐标进行初始化(无参构造函数)
        x=0;
        y=0;
    }
    public MyPoint(double x,double y){//有参构造方法
        this.x=x;
        this.y=y;
    }
    public double getX(){
        return x;
    }
    public void setX(double x){
        this.x=x;
    }
    public double getY(){
        return y;
    }
    public void setY(double y){
        this.y=y;
    }
    public static double getdistance(MyPoint p1,MyPoint p2){//计算两点之间的距离
         double distance = Math.sqrt(Math.pow((p1.getX()-p2.getX()), 2)+Math.pow((p1.getY()-p2.getY()), 2));
            return distance;//返回距离值
    }
}

运行结果:

posted @ 2019-09-18 18:50  路沛环  阅读(193)  评论(0编辑  收藏  举报