Scala, lesson 3
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.
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.
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.
"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:
| Operator | Meaning | Int example | Double example |
|---|---|---|---|
+ | add | 7 + 2 is 9 | 7.0 + 2 is 9.0 |
- | subtract | 7 - 2 is 5 | |
* | multiply | 7 * 2 is 14 | |
/ | divide | 7 / 2 is 3 | 7.0 / 2 is 3.5 |
% | remainder | 7 % 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).
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:
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 -> Doubleval parts = readLine().trim.split("\\s+") // "3 4" -> Array("3", "4")
val a = parts(0).toInt
val b = parts(1).toIntval avg = 10.0 / 3
println(f"Average: $avg%.2f") // Average: 3.33Each friend gets <n> slices
Leftover: <m>10
3Each friend gets 3 slices
Leftover: 121.521.5 C = 70.7 F