Java练习题 类 先创建一个Point类,然后定义Trianglele类。在Trianglele类中定义三个Point的实体来表示一个三角形的三个点,然后定义两个方法求三角形的周长、面积。

先创建一个Point类,然后定义Trianglele类。

在Trianglele类中定义三个Point的实体来表示一个三角形的三个点,再定义构造方法对这三个点进行初始化,然后定义两个方法求三角形的周长、面积。

定义一个测试类,在main()中创建一个对象,求给定三点的三角形的周长、面积。

 

package test1;
import java.util.*;

public class Main {
	public static void main(String args[]) 
	{
		Scanner sc = new Scanner(System.in);
		Point p1 = new Point(0, 0);
		Point p2 = new Point(3, 0);
		Point p3 = new Point(0, 4);
		Trianglele t1 = new Trianglele(p1, p2, p3);
		System.out.println("三角形的面积:" + t1.getArea());
		System.out.println("三角形的周长:" + t1.getPerimeter());
		sc.close();
	}
}
class Point
{
	double x, y;
	public Point(double x, double y)
	{
		this.x = x;
		this.y = y;
	}
}
class Trianglele
{
	private Point point1, point2, point3;
	private double a, b, c;
	public Trianglele(Point point1, Point point2, Point point3)
	{
		this.point1 = point1;
		this.point2 = point2;
		this.point3 = point3;
	}
	private void getSideLength()
	{//求三边边长
		a = Math.sqrt(Math.pow((point2.x - point1.x), 2) + Math.pow((point2.y - point1.y), 2));
		b = Math.sqrt(Math.pow((point3.x - point2.x), 2) + Math.pow((point3.y - point2.y), 2));
		c = Math.sqrt(Math.pow((point3.x - point1.x), 2) + Math.pow((point3.y - point1.y), 2));
	}
	public double getArea()
	{
		getSideLength();
		double p = (a + b + c) / 2.0;
		return Math.sqrt(p * (p-a)* (p-b) * (p-c));
	}
	public double getPerimeter()
	{
		return a + b + c;
	}
}

 

好的,您的第一个问题是如何在Java创建一个Point和Circle,以及如何让Circle调用Point类中方法函数。 Java创建一个Point可以参考下面的代码: public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } } 创建一个Circle并调用Point类中方法可以参考下面的代码: public class Circle { private Point center; private int radius; public Circle(Point center, int radius) { this.center = center; this.radius = radius; } public Point getCenter() { return center; } public int getRadius() { return radius; } public void setCenter(Point center) { this.center = center; } public void setRadius(int radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public double getPerimeter() { return 2 * Math.PI * radius; } public boolean contains(Point p) { double distance = Math.sqrt(Math.pow(p.getX() - center.getX(), 2) + Math.pow(p.getY() - center.getY(), 2)); return distance <= radius; } } 在Circle类中使用Point方法可以通过创建一个指向Point对象的引用变量,即将Point对象作为Circle一个属性来实现。以上代码中,Circle类中一个Point型的实例变量center,且在Circle类中调用了Point类中的getX()和getY()方法以计算圆的包含关系。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值