0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Josh Skeen, David Greenhalgh著 『Kotlinプログラミング』 章末問題に挑戦(第10章)

Last updated at Posted at 2020-12-16

 Josh Skeen, David Greenhalgh著『Kotlinプログラミング』には章末問題がある。残念なことに解答がないので、第8章に引き続き本を読み進めながら答案を記述する。
 もし回答に間違いや意見があれば、ぜひご指摘いただきたい。

第10章 章末問題 回答案

10.11 チャレンジ! タバーンメニューのフォーマット

10.12 チャレンジ! より高度なタバーンメニューのフォーマット

 10.11と10.12の課題をまとめて回答する。
 難しかったのは、商品名(name)と価格(price)の間に入れる(.)のパッティングをどのように入れるかであった。パティングの入れ方は本書にはないようなのでネットに掲載されているものを参考にした。もっといい(簡単な)既存の関数で処理する方法があればご教示いただきたい。

kotlin#Tavern.kt
import java.io.File

val menuList = File("data/tavern-menu-items.txt")
    .readText()
    .split("\n")

fun main() {
    println()
    println("10.11 チャレンジ! タバーンメニューのフォーマット")

    println()
    println("失敗例:商品名nameに含まれているスペースも*に置換されてしまっている。")
    println("*** Welcome to Taernyl's Folly ***")
    menuList.forEach { data ->
        val (_, name, price) = data.split(',')
        print("%-22s".format(name).replace(" ", "*"))       // 分かりやすくするため*を使用。最終的には.に変える
        println("%10s".format(price).replace(" ", "+"))     // 最終的には.に変える
    }

    println()
    println("成功例:")
    println("*** Welcome to Taernyl's Folly ***")
    menuList.forEach { data ->
        val (_, name, price) = data.split(',')
        print(name)
        for (i in name.length..21) {
            print("*")
        }
        println("%10s".format(price).replace(" ", "+"))
    }

    println()
    println("10.12 チャレンジ! より高度なタバーンメニューのフォーマット")
    println()
    println("*** Welcome to Taernyl's Folly ***")
    menuList.forEach { data ->
        val (type, name, price) = data.split(',')
        // タイプを表示(商品名の右端と価格の左端を基準にセンターリングできるように工夫)
        var tab = ((31 - 6 - type.length) / 2).toInt()
        var spaceBlock =""
        for(i in 0.. tab){
            spaceBlock = spaceBlock + " "
        }
        println(spaceBlock + "~[" + type + "]~")    
        // 商品名と価格を表示
        print(name)
        for (i in name.length..21) {
            print(".")
        }
        println("%10s".format(price).replace(" ", "."))
    }
}

第2章チャレンジ!答案
第3章チャレンジ!答案
第4章チャレンジ!答案
第7章チャレンジ!答案
第8章チャレンジ!答案
第10章チャレンジ!答案
第13章チャレンジ!答案

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?