Learn/Scala/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

Scala, lesson 3

Reading input and arithmetic

Programs become useful when they react to data. The simplest source of data is standard input (stdin): the text typed into the program, or the Input box when you run code here.

Reading a line

scala.io.StdIn.readLine() reads one line and returns it as a String, without the line break at the end. Import it once at the top of the file so you can write just readLine():

Each call reads the next line. If there are no lines left, readLine() returns null, so only read as many lines as the input promises.

Text is not a number

readLine() always gives you a String. Even if the line is 42, it's the text , and would give . Convert the text first:

2 exercises to try what you just read.

Exercise 1

Pizza split

Press Ctrl Enter or Check to test your code.

Exercise 2

Temperature converter

Press Ctrl Enter or Check to test your code.

"42"
"42" + 1
"421"

trim removes spaces around the text, which protects you from stray whitespace. If the text isn't a valid number, toInt throws a NumberFormatException and the program stops. For now, trust the input format the exercise gives you.

When several numbers share one line, split the line on whitespace and convert each piece:

Arithmetic operators

OperatorMeaningInt exampleDouble example
+add7 + 2 is 97.0 + 2 is 9.0
-subtract7 - 2 is 5
*multiply7 * 2 is 14
/divide7 / 2 is 37.0 / 2 is 3.5
%remainder7 % 2 is 1

The big one to remember: dividing two Ints gives an Int, and the fraction is thrown away. If you want a decimal result, make at least one side a Double, for example with count.toDouble / 2.

Scala follows the usual precedence rules: *, / and % happen before + and -. Use parentheses when you want a different order or when it makes the intent clearer: (a + b) * 2.

For things like square roots and rounding, use math: math.sqrt(16.0), math.abs(-3), math.max(a, b), math.round(2.6).

Printing decimals neatly

A Double prints with as many digits as it needs, which can look odd (0.1 + 0.2 prints 0.30000000000000004). To control the number of decimals, use the f interpolator:

Further reading

  • Scala 3 Book: Command-line I/O
  • Scala API: StdIn
  • Scala 3 Book: String Interpolation (the f interpolator)

A group of friends shares a pizza. Read the number of slices on the first line and the number of friends on the second line (always at least 1). Everyone gets the same whole number of slices, and the rest stays in the box. Print:

Sample input:

Sample output:

Read a temperature in Celsius (it may have a decimal point) and print it in Fahrenheit with exactly one decimal place. The formula is F = C * 9 / 5 + 32.

Sample input:

Sample output:

Print the Celsius value exactly as it was typed (after trimming spaces).

import scala.io.StdIn.readLine

@main def greet(): Unit =
  val name = readLine()
  println(s"Hello, $name!")
val count = readLine().trim.toInt        // String -> Int
val price = readLine().trim.toDouble     // String -> Double
val parts = readLine().trim.split("\\s+")   // "3 4" -> Array("3", "4")
val a = parts(0).toInt
val b = parts(1).toInt
val avg = 10.0 / 3
println(f"Average: $avg%.2f")   // Average: 3.33
Each friend gets <n> slices
Leftover: <m>
10
3
Each friend gets 3 slices
Leftover: 1
21.5
21.5 C = 70.7 F