vmp
vmp

Reputation: 2420

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

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?

Upvotes: 11

Views: 7933

Answers (2)

Aakash Mathai
Aakash Mathai

Reputation: 21

You can use the Java.util.Scanner in the scala programs. This supports the functions of Scanner that is available in java

import java.util.Scanner;
object Addition{
 def main(args: Array[String]){
  var scanner = new Scanner(System.in); //defining scanner object
  println("Enter two numbers : ");
  var a = scanner.nextInt();            //reading space separated input
  var b = scanner.nextInt();
  println("The result is : "+(a+b));
 }
}

Upvotes: 0

Uwe L. Korn
Uwe L. Korn

Reputation: 8816

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)

Upvotes: 28

Related Questions