Java, lesson 3
Programs become useful when they work on data you give them. Every exercise on this site feeds your program text on standard input (stdin), one line at a time, and checks what you print.
The standard way to read lines in Java is a BufferedReader wrapped around System.in:
A few new things appear here:
import lines at the top let you use classes from other packages by their short name.readLine() returns the next line without the line break, or null when there is no more
input.readLine may throw an
. Writing on says "if that happens, just stop". You
will learn proper error handling in a later lesson.2 exercises to try what you just read.
IOExceptionthrows IOExceptionmainreadLine always gives you a String. The text "42" is not the number 42; you cannot do
maths with it. Convert it first:
trim() removes stray spaces around the text, which parseInt would otherwise reject.
When several numbers share one line, split the line on whitespace:
"\\s+" means "one or more whitespace characters". (You may also see java.util.Scanner used
for input. It is convenient but slower; BufferedReader is the reliable choice for big inputs.)
| Operator | Meaning | int example |
|---|---|---|
+ | add | 7 + 2 is 9 |
- | subtract | 7 - 2 is 5 |
* | multiply | 7 * 2 is 14 |
/ | divide | 7 / 2 is 3 |
% | remainder | 7 % 2 is 1 |
Watch out for /. When both sides are integers, Java does integer division and throws away
the fraction: 7 / 2 is 3, not 3.5. If either side is a double, you get a decimal result:
7 / 2.0 is 3.5. To divide two int variables as decimals, cast one of them:
(double) a / b.
The remainder operator % pairs nicely with /: 17 sweets shared by 5 children is 17 / 5 = 3
each, with 17 % 5 = 2 left over.
Java follows the usual precedence rules (*, /, % before + and -). Use parentheses when
in doubt. Shortcuts update a variable in place: score += 10;, lives -= 1;, count++;.
printf with %.2f rounds a double to two decimal places for display, which is usually what
you want for money or measurements. Math.round(x) rounds to the nearest whole number and
returns a long.
A group shares a restaurant bill. The input has two lines: the total in cents (a whole number), then the number of people. Everyone pays the same whole number of cents, and whatever cannot be split evenly is left over (the person who booked covers it).
Print two lines: Each: <cents> and Left over: <cents>.
Sample input:
Sample output:
Read one temperature in degrees Celsius (it may have a decimal point) and print it in degrees
Fahrenheit, rounded to one decimal place. The formula is F = C × 9 / 5 + 32.
Be careful: 9 / 5 on two integers is 1, not 1.8.
Sample input:
Sample output:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String name = in.readLine();
System.out.println("Hi, " + name + "!");
}
}int age = Integer.parseInt(in.readLine().trim());
double price = Double.parseDouble(in.readLine().trim());String[] parts = in.readLine().trim().split("\\s+"); // "3 4" -> ["3", "4"]
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);10000
3Each: 3333
Left over: 13798.6