Java语言程序设计 例题10.4(Mypoint类)

10.4 (The MyPoint class) Design a class named MyPoint to represent a point with 
x- and y-coordinates. The class contains:
 ■ The data fields x and y that represent the coordinates with getter 
methods.
 ■ A no-arg constructor that creates a point (0, 0).
 ■ A constructor that constructs a point with specified coordinates.
 ■ A method named distance that returns the distance from this point to a 
specified point of the MyPoint type.
 ■ A method named distance that returns the distance from this point to 
another point with specified x- and y-coordinates.
Draw the UML diagram for the class and then implement the class. Write a 
test program that creates the two points (0, 0) and (10, 30.5) and displays the 
distance between them.

10.4(Mypoint类)设计一个名为MyPoint的类来表示一个具有x和y坐标的点。类包含:

 ■ 数据字段x和y表示带有getter方法的坐标

 ■ 创建点(0,0)的无参数构造函数.

 ■ 构造具有指定坐标的点构造函数

 ■ 名为distance的方法,它返回这个点到MyPoint指定点的距离

 ■ 名为distance的方法,它返回这个点到另一个特定点的特定坐标x,y的距离

 绘制类的UML图,但后实现类.编写一个测试程序,创建两个点(0,0)和(10,30.5),并显示它们之间的距离

代码如下:


public class Unite10Test4
{
	public static void main(String[] args) 
	{
		MyPoint m1=new MyPoint(0,0);
		MyPoint m2=new MyPoint(10,30.5);
		double x=m1.getX();
		double y=m1.getY();
		System.out.println("它们之间的距离为: "+m2.distance(x, y));
	}

}
class MyPoint
{
	private double x;
	private double 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 MyPoint() 
	{
		
	}
	public MyPoint(double x,double y) 
	{
		this.x=x;
		this.y=y;
	}
	public double distance() 
	{
		return Math.sqrt((this.x*this.x)-(x*x)+(this.y*this.y)-(y*y));
	}
	public double distance(double x,double y) 
	{
		return Math.sqrt((this.x*this.x)-(x*x)+(this.y*this.y)-(y*y));
	}
}

结果如下:

 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

差劲的厉害了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值