java · level 1 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Java is a calculator that never gets tired.
Each does one job: + adds, - takes away, * multiplies and / divides. Brackets go first, then * and /, then + and -, as in maths lessons.
Watch out with /. When both numbers are int, Java gives a whole number and drops the rest, so 7 / 2 is 3. Make one of them a double, like 7.0 / 2, to get 3.5.
% gives the , what is left over after sharing out. Share 7 sweets between 2 friends: each gets 3, and 7 % 2 is the 1 sweet left over.
public class Main {
public static void main(String[] args) {
System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
System.out.println(7 / 2);
System.out.println(7.0 / 2);
System.out.println(7 % 2);
}
} Whole-number division never rounds up, so 9 / 10 is 0.
guess first
Ten sweets, four friends. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
int sweets = 10;
int friends = 4;
System.out.println(sweets / friends);
}
}
your turn
Your turn. Share out the stickers.
Choose how many stickers you have and how many friends to share them with. Use whole numbers, and at least 1 friend. Then press run.
output
press run to see what happens
fix it
The pizza bill is too high. Can you fix it?
output
press run to see what happens
- Java does
/before+. Which part is being divided by 2 on line 5? - Only drinks gets halved, then pizza is added on. The whole bill should be split between two.
- Put brackets round
pizza + drinkson line 5, then press run.
nailed it
you turned java into a calculator. :D
- Brackets go first, then
*and/, then+and-. - An
intdivided by anintdrops the decimals. %gives the remainder, what is left over.
new words in your collection
- operator
- remainder
This lesson isn’t saved. A free account remembers every lesson you finish.