Read multiple variables in the same line (Scala)

Asked

Viewed 115 times

0

I need to read three variables in the same line in Scala, I read an answer in English but the method did not work, "readline" and "toInt" are not recognized. Follow my code. If anyone knows a way that works.

object main {
  def main(args: Array[String]): Unit = {
    val Array(cd1,nr1,vr1) = readLine.split(" ").map(_.toInt)
    val Array(cd2,nr2,vr2) = readLine.split(" ").map(_.toInt)
    val total : Double = nr1*vr1 + nr2+vr2
    println(f"VALOR A PAGAR = $total%.2f")
  }

}

1 answer

0


I decided here guys, but if anyone has a less verbose and/ or more sophisticated solution and you do not need to call a library I would be grateful to know. Follows the code:

import java.util.Scanner
import java.util.Locale

object main {
  def main(args: Array[String]): Unit = {
    Locale.setDefault(Locale.US)
    /* Criei um objeto scanner, setando como entrada dele o teclado (StdIn) 
separando os frames por espaço (" ") */
    val scan  = new Scanner(scala.io.StdIn.readLine()).useDelimiter(" ")
    val cd1 : Int = scan.nextInt()
    val nr1 : Int = scan.nextInt()
    val vr1 : Double = scan.nextDouble()
    val scan2  = new Scanner(scala.io.StdIn.readLine()).useDelimiter(" ")
    /* Como eu faço leitura de dois inputs contendo 3 dados cada eu criei um segundo
scanner para ler os dados do segundo input. */
    val cd2 : Int = scan2.nextInt()
    val nr2 : Int = scan2.nextInt()
    val vr2 : Double = scan2.nextDouble()
    val total : Double = nr1*vr1 + nr2*vr2
    println(f"VALOR A PAGAR: R$$ $total%.2f")
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.