如何正确对齐输出

时间:2018-07-18 18:17:33

标签: scala

我的值如下:

val x = List((("Burger and chips",4.99),4.99,1), (("Pasta & Chicken with Salad",8.99), 8.99,2), (("Rice & Chicken with Chips",8.99), 8.99,2))

打印后我得到这个:

x.foreach(x => println(x._3 + " x " + x._1 +"\t\t\t\t"+"$"+x._2 * x._3 ))

1 x (Burger and chips,4.99)             $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

但是我想要这个结果:

1 x (Burger and chips,4.99)                         $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

我知道文字大小是造成问题的原因,但是有没有解决的办法?

谢谢

1 个答案:

答案 0 :(得分:2)

Scala的"f interpolator"为此有用:

x.foreach { 
  case (text, price, amount) => println(f"$amount x $text%-40s $$${price*amount}") 
}

// prints:
1 x (Burger and chips,4.99)                  $4.99
2 x (Pasta & Chicken with Salad,8.99)        $17.98
2 x (Rice & Chicken with Chips,8.99)         $17.98