codewars034: TDD Area Calculations

本文介绍了一个使用Java实现的图形计算器程序,能够计算不同形状的面积,并通过BigDecimal确保计算结果的精度。涉及Square(正方形)、Rectangle(矩形)、Circle(圆形)及Triangle(三角形)等几何形状。

Source

package codewars;
import java.math.BigDecimal;
public class Calculator{
    public double getTotalArea(Shape shape){
        return new BigDecimal(Double.toString(shape.getArea())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }    
    public double getTotalArea(Shape... shapes){
        double total = 0;
        for(Shape x : shapes){
            total += x.getArea();
        }    
        return new BigDecimal(Double.toString(total)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }    
}

interface Shape{
    public double getArea();
}
class Square implements Shape{
    private double side;
    public Square(double side){
          this.side = side;
    }    
    @Override
    public double getArea(){
        return side * side;
    }        
}
class Rectangle implements Shape{
    private double height;
    private double width;
    public Rectangle(double height, double width){
        this.height = height;
        this.width = width;
    }    
    @Override
    public double getArea(){
        return height * width;
    }    
}

class Circle implements Shape{
    private double radius;
    public Circle(double radius){
        this.radius = radius;
    }    
    @Override
    public double getArea(){
        return Mathi.PI * radius * radius;
    }    
}

class Triangle implements Shape{
    private double base;
    private double height;
    public Triangle(double base, double height){
        this.base = base;
        this.height = height;
    }        
    @Override
    public double getArea(){
        return base * height / 2;
    }        
}

转载于:https://my.oschina.net/u/553266/blog/812166

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值