Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, how to read more than one integer in one line in and get them in one variable each?

Tags:

io

integer

scala

here is my code:

object theater extends App {

    val m = readInt
    val n = readInt
    val a = readInt

    val c1 = m/a + (if(m%a == 0) 0 else 1)
    val c2 = n/a + (if(n%a == 0) 0 else 1)
    print(c1 + c2)
}

But the input format is: 3 integers in the same line. But for 3 integers in one line scala will consider that as a string. How can I read that string and get the 3 values in the 3 separated variables?

like image 530
vmp Avatar asked Oct 07 '12 13:10

vmp


People also ask

How to read multiple integer values from a single line of input in java?

To do this, we could read in the user's input String by wrapping an InputStreamReader object in a BufferedReader object. Then, we use the readLine() method of the BufferedReader to read the input String – say, two integers separated by a space character. These can be parsed into two separate Strings using the String.

How do you input integers in Scala?

Using a thread to poll the input-readLine: // keystop1.sc // In Scala- or SBT console/Quick-REPL: :load keystop1.sc // As Script: scala -savecompiled keystop1.sc @volatile var isRunning = true @volatile var isPause = false val tInput: Thread = new Thread { override def run: Unit = { var status = "" while (isRunning) { ...

How to get two inputs in same line in java?

//... do the above declaration of array for ( int i = 0; i < n; i++){ for( int j = 0; j < m; j++){ arr[i][j] = sc. nextInt() } sc. nextLine(); // you need to eat the \n here. }

How to take String and int input in one line in java?

split(" "); name[x] = Value[0]; number[x] = Integer. parseInt(Value[1]); with mine: name[x] = in. next(); number[x] = in. nextInt(); .


1 Answers

You could use the following code which will read a line and use the first 3 whitespace separated tokens as the input. (Expects e.g. "1 2 3" as the input on one line)

val Array(m,n,d) = readLine.split(" ").map(_.toInt)
like image 86
Uwe L. Korn Avatar answered Sep 30 '22 08:09

Uwe L. Korn