简体   繁体   中英

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?

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

val Array(m,n,d) = readLine.split(" ").map(_.toInt)

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));
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM