0

I'm new to scala and wanted to iterate over a list[list[(String, Double, Int)]] to print each inner list elements, do some calculation and then align the result of the calculation. I'm cal each item in the inner list.

For example:

Data:

val x: List[List[(String, Double, Int)]] = List(List(("Coke", 2.50, 1),("Pepsi", 2.50, 2)), List(("Red Wine", 4.50, 2), ("Beer", 3.00, 2)))

Using the below to print out:

for ((list, tableIdx) <- x.zipWithIndex) {
   println("Table" + (tableIdx+1) + "order is:\n"
      + list.mkString("\n")
          )
}

the output is:

Table1order is:
(Coke,2.5,1)
(Pepsi,2.5,2)
Table2order is:
(Red Wine,4.5,2)
(Beer,3.0,2)

Desired output:

Table 1 Order:

  1 X Coke                  $2.50
  2 X Pepsi                 $5.00
               Subtotal =   $7.50

Table 2 Order:

  2 X Red Wine              $9.00
  2 X Beer                  $6.00
                Subtotal =  $15.00

               Bill Total = $23.50 

So my question is how to get the desired results please

Thanks

zeynab23
  • 19
  • 1
  • 5
  • Additional hint for your specific case: `val (name, itemPrice, amount) = ("Coke", 2.5, 42); println(f" ${amount}%3d X ${name}%-30s $$${itemPrice * amount}%.2f")` gives output `42 X Coke $105.00` with the right number of spaces (not visible in comment, unfortunately). The rest should be trivial to do with line breaks and some perseverance. – Andrey Tyukin Jul 31 '18 at 15:42
  • @AndreyTyukin, where is the similar question and please can you complete your hint with example. I'm new to scala. – zeynab23 Jul 31 '18 at 16:00
  • The list of duplicates is at the top, [this answer](https://stackoverflow.com/a/51408747/2707792) in particular seems to do almost exactly what you want, even the `x`s and the `$`-signs are the same. My hint above contains a compilable code snippet, just paste it in the console and run it. Does it solve your problem? – Andrey Tyukin Jul 31 '18 at 16:04
  • @AndreyTyukin, thanks for your help. But how can i use it in the for comprehension. Thats what i'm struggling with. – zeynab23 Jul 31 '18 at 16:16
  • Just nest two loops, write the list-headers with the outer loop, then each line with the inner loop: `for ((list, tableIdx) <- x.zipWithIndex) { println("Table" + (tableIdx+1) + "order is:\n"); for ((name, price, n) <- list) { println("funnyFormatStringAsAbove") }; /* print total price */ }`. Keyword: "nested loops". – Andrey Tyukin Jul 31 '18 at 16:22
  • @AndreyTyukin, thanks for your help – zeynab23 Jul 31 '18 at 16:49

0 Answers0