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

Groovy, lesson 3

Reading input and arithmetic

Programs get interesting when they react to data. The simplest source of data is standard input (stdin): text typed by a user or, here, supplied by the tests.

Reading lines

System.in is the standard input stream. Groovy adds a newReader() method to it, which gives you a reader with a handy readLine():

Each readLine() call returns the next line as a string, without the new line at the end. When the input runs out it returns null. Create the reader once and reuse it for every line.

If you want all the lines at once, System.in.readLines() returns them as a list. You'll use lists properly in lesson 7.

Text to numbers

Input always arrives as text. Convert it with Groovy's conversion methods:

2 exercises to try what you just read.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Temperature converter

Press Ctrl Enter or Check to test your code.

.trim() removes spaces around the text, which would otherwise make the conversion fail. .toInteger(), .toLong(), .toDouble() and .toBigDecimal() throw an exception if the text is not a number. You can also write line as int.

Arithmetic

OperatorMeaningExample
+ - *add, subtract, multiply3 * 4 is 12
/divide7 / 2 is 3.5
intdivwhole division7.intdiv(2) is 3
%remainder7 % 2 is 1
**power2 ** 10 is 1024

Look closely at /. In Java, 7 / 2 is 3, because dividing two integers throws the fraction away. Groovy chose the result a person would expect: dividing two integers gives an exact BigDecimal, 3.5. When you really want whole-number division, use intdiv. Remember this when porting code between Java and Groovy.

Precedence follows maths: ** first, then *, / and %, then + and -. Parentheses make the order explicit when in doubt.

Rounding when printing

String.format (and printf) can round a number for display. %.1f keeps one decimal place:

The value itself is unchanged; only the printed text is rounded.

Further reading

  • Operators: arithmetic
  • Syntax: numbers and the division operator

Every pizza has 8 slices. Read the number of people (first line) and the number of pizzas (second line). Share the slices equally, then print how many whole slices each person gets and how many are left over. There is always at least one person.

Sample input:

Sample output:

Read a temperature in degrees Celsius (it may have a decimal part) and print it in Fahrenheit, rounded to one decimal place. The formula is F = C * 9 / 5 + 32.

Sample input:

Sample output:

def reader = System.in.newReader()
def name = reader.readLine()
println "Hi, ${name}!"
int age = reader.readLine().trim().toInteger()
def height = reader.readLine().trim().toBigDecimal()
println age + 1
def km = 42.195
println String.format("%.1f miles", km / 1.609)   // 26.2 miles
5
3
Slices each: 4
Left over: 4
36.6
97.9