Java编写一个测试程序,提示用户输入三角形的三边、颜色和三角形是否是实心的布尔值,之后创建一个三角形对象,并使用输入设置颜色和填充属性。该程序应显示面积、周长、颜色以及实心与否等信息。
时间: 2024-05-07 08:18:00 浏览: 29
用java编写有关判断是否为三角形
5星 · 资源好评率100%
代码如下:
```java
import java.util.Scanner;
public class TriangleTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入三角形的三边长度:");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
System.out.print("请输入三角形的颜色:");
String color = input.next();
System.out.print("请输入三角形是否实心(true/false):");
boolean isFilled = input.nextBoolean();
Triangle triangle = new Triangle(side1, side2, side3);
triangle.setColor(color);
triangle.setFilled(isFilled);
System.out.println("三角形的面积为:" + triangle.getArea());
System.out.println("三角形的周长为:" + triangle.getPerimeter());
System.out.println("三角形的颜色为:" + triangle.getColor());
System.out.println("三角形是否实心:" + triangle.isFilled());
}
}
class Triangle extends GeometricObject {
private double side1;
private double side2;
private double side3;
public Triangle() {
this.side1 = 1.0;
this.side2 = 1.0;
this.side3 = 1.0;
}
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1() {
return side1;
}
public void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
@Override
public String toString() {
return "Triangle{" +
"side1=" + side1 +
", side2=" + side2 +
", side3=" + side3 +
'}';
}
}
class GeometricObject {
private String color;
private boolean filled;
public GeometricObject() {
this.color = "white";
this.filled = false;
}
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
}
```
这里我们定义了一个 `Triangle` 类来表示三角形,继承了一个 `GeometricObject` 类,其中 `GeometricObject` 类包含了颜色和是否填充的属性。在 `TriangleTest` 类中,我们使用 `Scanner` 类来获取用户输入的三边长度、颜色和是否填充,并创建了一个 `Triangle` 对象。然后我们调用 `Triangle` 类中的方法来获取面积和周长,并显示颜色和是否填充等信息。
阅读全文