1 编写一个类Computer,类中含有一个求n的阶乘的方法。将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参数决定),并将结果输出。
代码
computer类
package com.ws.www;
public class Computer {
public int Factorial(int n) {
int product = 1;
if (n == 1)
product *= n;
else {
product = n * Factorial(n - 1);
}
return product;
}
}
int product = 1;
if (n == 1)
product *= n;
else {
product = n * Factorial(n - 1);
}
return product;
}
}
APP
package com.ws.www;
import com.ws.www.Computer;
public class App {
public static void main(String[] args) {
Computer c=new Computer();
System.out.println("6的阶乘为"+c.Factorial(6));
}
}
import com.ws.www.Computer;
public class App {
public static void main(String[] args) {
Computer c=new Computer();
System.out.println("6的阶乘为"+c.Factorial(6));
}
}
运行

2
设计一个MyPoint类,表示一个具有x坐标和y坐标的点,该类包括:
- 两个私有成员变量x和y表示坐标值;
- 成员变量x和y的访问器和修改器
- 无参构造方法创建点(0,0);
- 一个有参构造方法,根据参数指定坐标创建一个点;
- distance方法(static修饰)返回参数为MyPoint类型的两个点对象之间的距离。
编写主类Test,在主类中输入两点坐标,创建两个点对象,利用distance()方法计算这两个点之间的距离。
代码
package com.po.www;
public class MyPoint {
private double x;
private double 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 void distance(MyPoint m){
double dis=(double) Math.sqrt(Math.pow(getX()-m.getX(),2)+Math.pow(this.getY()-m.getY(),2)) ;
System.out.println("两点间的距离是"+dis);
}
public static void main(String[] args) {
//调用午餐构造方法
MyPoint my=new MyPoint();
//调用有参构造方法
MyPoint my1=new MyPoint(1.0,2.0);
my.distance(my1);
}
}
private double x;
private double 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 void distance(MyPoint m){
double dis=(double) Math.sqrt(Math.pow(getX()-m.getX(),2)+Math.pow(this.getY()-m.getY(),2)) ;
System.out.println("两点间的距离是"+dis);
}
public static void main(String[] args) {
//调用午餐构造方法
MyPoint my=new MyPoint();
//调用有参构造方法
MyPoint my1=new MyPoint(1.0,2.0);
my.distance(my1);
}
}
运行
