Java 语言程序设计(第十版) 第十三章 第1题

13.1

设计一个扩展自抽象类 GeometricObject 的新的 Triangle 类。绘制 Triangle 类和 GeometricObject 类的 UML 图并实现 Triangle 类。编写一个测试程序,提示用户输入三角形的三条边、一种颜色以及一个表明该三角形是否填充的布尔值。程序应该根据用户的输入,使用这些边以及颜色和是否填充的消息,创建一个 Triangle 对象。程序应该显示面积、周长、颜色以及真或假来表明是否被填充。

import java.util.Scanner;

abstract class GeometricObject {
    private String color;
    private Boolean filled;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Boolean getFilled() {
        return filled;
    }
    public void setFilled(Boolean filled) {
        this.filled = filled;
    }
    public abstract double getArea();
    public abstract double getPremeter();
}
class Triangle extends GeometricObject {
    private double one;
    private double two;
    private double three;
    public void setOne(double one) {
        this.one = one;
    }
    public void setTwo(double two) {
        this.two = two;
    }
    public void setThree(double three) {
        this.three = three;
    }
    @Override
    public double getArea() {
        double p = (one + two + three)/2;
        return Math.sqrt(p * (p - one) * (p - two) * (p - three));
    }
    @Override
    public double getPremeter() {
        return one + two + three;
    }
    @Override
    public String toString() {
        return "三角形面积:" + getArea() + " 周长:" + getPremeter() + " 颜色:" + getColor() + " 是否被填充:" + getFilled();
    }
}

测试:

public class Test13_1 {
    public static void main(String[] args) {
        Triangle a = new Triangle();
        Scanner in = new Scanner(System.in);
        System.out.println("Please input three sides:");
        a.setOne(in.nextDouble());
        a.setTwo(in.nextDouble());
        a.setThree(in.nextDouble());
        System.out.println("Please input the color:");
        a.setColor(in.next());
        System.out.println("Please input whether the triangle is filled:(true or false)");
        a.setFilled(in.nextBoolean());
        System.out.println(a.toString());
    }
}

结果:

Please input three sides:
3 5 6
Please input the color:
red
Please input whether the triangle is filled:
true
三角形面积:7.483314773547883 周长:14.0 颜色:red 是否被填充:true

类图:

这里写图片描述

  • 11
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值