開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 4(classes and objects - A Bit of Class)、Pool Puzzle(117)の解答を求めてみる。
コード
class Rectangle(var width: Int, var height: Int) {
val isSquare: Boolean
get() = width == height
val area: Int
get() = width * height
}
fun main() {
val r = arrayOf(
Rectangle(1, 1),
Rectangle(1, 1),
Rectangle(1, 1),
Rectangle(1, 1)
)
for (x in 0..3) {
r[x].width = (x + 1) * 3
r[x].height = x + 5
print("Rectangle $x has area ${r[x].area}. ")
println("It is ${if (r[x].isSquare) "" else "not "}a square.")
}
println()
// 他のループでの方法
for (x in 0 until r.size) {
r[x].width = (x + 1) * 3
r[x].height = x + 5
print("Rectangle $x has area ${r[x].area}. ")
println("It is ${if (r[x].isSquare) "" else "not "}a square.")
}
println()
for ((x, rect) in r.withIndex()) {
rect.width = (x + 1) * 3
rect.height = x + 5
print("Rectangle $x has area ${rect.area}. ")
println("It is ${if (rect.isSquare) "" else "not "}a ssquare.")
}
}入出力結果
Rectangle 0 has area 15. It is not a square. Rectangle 1 has area 36. It is a square. Rectangle 2 has area 63. It is not a square. Rectangle 3 has area 96. It is not a square. Rectangle 0 has area 15. It is not a square. Rectangle 1 has area 36. It is a square. Rectangle 2 has area 63. It is not a square. Rectangle 3 has area 96. It is not a square. Rectangle 0 has area 15. It is not a ssquare. Rectangle 1 has area 36. It is a ssquare. Rectangle 2 has area 63. It is not a ssquare. Rectangle 3 has area 96. It is not a ssquare. Process finished with exit code 0
0 コメント:
コメントを投稿