Chapter 1
Input and output
Every program in this chapter does the same thing: it reads something, calculates with it and prints a result. That's all you need for the first tasks.
The frame is always the same. Your code goes between the curly braces of main, and Java runs it line by line from top to bottom. What public class and static mean exactly comes in later chapters. Until then, just leave the frame as it is.
Output and variables
System.out.println(...) prints a line. A variable is a named place that stores a value. When you create one, you put its type in front:
intfor whole numbers, e.g.int age = 19;doublefor decimal numbers, e.g.double price = 4.99;(with a dot, not a comma)Stringfor text in double quotes, e.g.String name = "Ada";
+ joins texts and values together. Every statement ends with a semicolon.
Try it: change the name or the age and run the example again.
Reading input and calculating
A Scanner reads what someone types into the console. nextInt() gets the next whole number, nextDouble() the next decimal number and nextLine() a whole line of text. Spaces and line breaks between numbers don't matter.
Java calculates with +, -, *, / and %. Two things are new:
- If you divide two
intvalues, the decimal places are dropped:17 / 5gives3. %(modulo) gives the remainder of the division:17 % 5gives2.
As soon as a decimal number is involved, Java keeps the decimal places, for example / 2.0 instead of / 2.
The “Input” field holds what the program reads. Change the numbers and watch the result and the remainder change.
Nice formatting with printf
Decimal numbers often have lots of decimal places. System.out.printf lets you decide how a value looks. The text contains placeholders that are replaced, in order, by the values after it:
%.2f: decimal number with exactly two decimal places (rounded)%d: whole number%s: text%n: line break (printfdoesn't add one by itself)
Common mistakes
Integer division
double average = (2 + 3) / 2;gives2.0, not2.5. The division happens with twointvalues, and only then is the result stored in adouble. Fix: divide by2.0.Plus joins text
Once there's a text on the left,
+just appends everything:System.out.println("Sum: " + 2 + 3); // Sum: 23 System.out.println("Sum: " + (2 + 3)); // Sum: 5So put calculations in the output in parentheses.
Typos the compiler reports
Java is case-sensitive: it doesn't know
system.out.printlnorstring. If a semicolon is missing, the compiler reports';' expected. The line number in the message usually points to that spot or the line before it.The output has to match exactly
The tests compare your output character by character. A missing space, an extra comma or
printinstead ofprintlnis enough to fail a test. Compare your output carefully with the task's example.