Groovy, lesson 3
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.
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.
Input always arrives as text. Convert it with Groovy's conversion methods:
2 exercises to try what you just read.
.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.
| Operator | Meaning | Example |
|---|---|---|
+ - * | add, subtract, multiply | 3 * 4 is 12 |
/ | divide | 7 / 2 is 3.5 |
intdiv | whole division | 7.intdiv(2) is 3 |
% | remainder | 7 % 2 is 1 |
** | power | 2 ** 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.
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.
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 + 1def km = 42.195
println String.format("%.1f miles", km / 1.609) // 26.2 miles5
3Slices each: 4
Left over: 436.697.9