JAVA程序设计(自主模式)-编写一个三角形类,能根据输入的3个double类型数据构造三角形对象

编程练习题2

 

(100/100 分数)

编写一个三角形类,能根据输入的3个double类型数据构造三角形对象,定义三个构造方法。
如果这3个数据满足构成三角形的条件,直接构造三角形。否则,如果3个数的最大值大于0,则自动构造以最大值为边的等边三角形。如果最大值也不大于0,则将三角形类的三边都初始化为0。
再定义一个getArea方法,计算所构造的三角形的面积,返回类型为double。
最后,编写main方法,测试getArea方法,计算三角形的面积。

输入:
输入三个有理数,中间用空格隔开。例如:
8.9 6.4 7.2

输出:
输出三角形的面积。例如:
22.78812396293297

Java:

import java.util.Scanner;

public class Main
{

	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		double x, y, z;
		x = sc.nextDouble();
		y = sc.nextDouble();
		z = sc.nextDouble();
		sc.close();
		
		Triangle t = new Triangle(x, y, z);
		System.out.println(t.getArea());
	}

}

class Triangle
{
	private double x, y, z;
	public Triangle(double x, double y, double z)
	{
		double max = -1;
		boolean flag = false;
		if (x > 0 && y > 0 && z > 0)
		{
			if (x + y > z && x + z > y && y + z > x)
			{
				this.x = x;
				this.y = y;
				this.z = z;
				flag = true;
				
			}
			else
			{
				max = x > y ? x : y;
				max = max > z ? max : z;
			}
		}
		else
		{
			max = x > y ? x : y;
			max = max > z ? max : z;
		}
		
		if (max < 0)
			max = 0;
		if (!flag)
			this.x = this.y = this.z = max;
	}
	public double getArea()
	{
		double p = (x + y + z)/2;
		return Math.sqrt(p * (p - x) * (p - y) * (p - z));
	}
}

 

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为您解答关于 Eclipse 编写三角形的问题。 1. 首先,在 Eclipse 中创建一个新的 Java 项目,命名为 Trival。 2. 在该项目中创建一个新的 Java ,命名为 Trival,并声明三个私有属性 buttom、height 和 area,代码如下: ``` public class Trival { private double buttom; private double height; private double area; } ``` 3. 创建默认构造方法,将 buttom 和 height 属性默认设置为 1.0,将 area 属性初始化为 0.0,代码如下: ``` public Trival() { this.buttom = 1.0; this.height = 1.0; this.area = 0.0; } ``` 4. 创建一个构造方法,可以为 buttom 和 height 属性赋初值,代码如下: ``` public Trival(double buttom, double height) { this.buttom = buttom; this.height = height; this.area = 0.0; } ``` 5. 创建一个方法 findArea(),用于计算三角形的面积,代码如下: ``` public void findArea() { this.area = 0.5 * this.buttom * this.height; } ``` 6. 在 Trival 中添加一个 main() 方法,用于测试该是否正确,代码如下: ``` public static void main(String[] args) { Trival t1 = new Trival(); Trival t2 = new Trival(2.0, 3.0); t1.findArea(); t2.findArea(); System.out.println("t1 area is " + t1.area); System.out.println("t2 area is " + t2.area); } ``` 7. 运行 main() 方法,输出结果如下: ``` t1 area is 0.5 t2 area is 3.0 ``` 可以看到,Trival 实现正确。 希望这个例子能够帮助您理解如何在 Eclipse 中编写程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值