编写三角形类,通过构造方法给各边长赋值,构建计算三角形面积的方法,创建单例对象TestTriangle,输出三角形的类别,边长及面积。(等边三角形,等腰三角形,直角三角形)scala代码
时间: 2024-10-21 12:07:14 浏览: 17
在Scala中,我们可以定义一个`Triangle`类,包含边长属性和计算面积的方法。然后为了满足单例模式,我们创建一个`TestTriangle`类,其中只有一个实例并提供获取该实例的方法。下面是示例代码:
```scala
// 定义Triangle类
class Triangle(side1: Double, side2: Double, side3: Double) {
require(side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1, "Invalid triangle sides")
def isEquilateral: Boolean = side1 == side2 && side2 == side3
def isIsosceles: Boolean = side1 != side2 && side1 != side3 && side2 != side3
def isRightangled: Boolean = Math.pow(side1, 2) + Math.pow(side2, 2) == Math.pow(side3, 2)
// 计算面积,这里假设海伦公式
def area: Double = {
val semiperimeter = (side1 + side2 + side3) / 2.0
math.sqrt(semiperimeter * (semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - side3))
}
}
// 创建单例的TestTriangle类
object TestTriangle {
private[this] var instance: Triangle = null
def getInstance(): Triangle = {
if (instance == null) {
instance = new Triangle(5.0, 5.0, 5.0) // 示例为等边三角形,你可以修改这里的参数
}
instance
}
def main(args: Array[String]): Unit = {
val triangle = getInstance()
// 判断三角形类别
if (triangle.isEquilateral) println("This is an Equilateral Triangle")
else if (triangle.isIsosceles) println("This is an Isosceles Triangle")
else if (triangle.isRightangled) println("This is a Right-Angled Triangle")
println(s"Side lengths: ${triangle.side1}, ${triangle.side2}, ${triangle.side3}")
println(s"Area: ${triangle.area} square units")
}
}
```
阅读全文