B4Coder
0%
LessonAbout 5 min

Chapter 1 · Lesson 3 of 5

03. Numbers and sums

Java can do sums. Print them and it shows the answer, and join numbers to words with +.

Numbers go straight into println, without quotes. If you give it a sum, Java works it out first and prints the answer. Join words and numbers with +: put the sum in brackets so it's worked out before it's joined.

Java
public class Main {    public static void main(String[] args) {        System.out.println(12);        System.out.println(7 + 5);        System.out.println("6 times 7 is " + (6 * 7));        System.out.println("Oops: " + 7 + 5);    }}

It shows

12
12
6 times 7 is 42
Oops: 75

See the last line? Without brackets, Java joins left to right: "Oops: " + 7 makes the text Oops: 7, then + 5 adds 5 on the end. Brackets fix it.

Use + and - as usual, * to multiply, / to divide, and % for what's left over after dividing.

Your turn

1Steps

  1. 1A school hall has 18 rows of 25 chairs. Print Chairs: and the number of chairs, worked out by Java with *.
  2. 2Then print Seconds in an hour: and 60 * 60, also worked out by Java.

Write it in Main.java, in public class Main. If it reads input, put the answers in Program input, under the terminal.

Use: System.out.println

Starting code

The editor starts empty. Copy this into it to begin, or write your own from scratch.

Java
public class Main {    public static void main(String[] args) {        System.out.println("Chairs: ");    }}

2Expected output

It should show

Chairs: 450
Seconds in an hour: 3600

3Hints

Stuck? Open one hint at a time: each gives a bit more help.

Hint 1

Join the words and the sum with +, and put the sum in brackets.

Hint 2

The first line is System.out.println("Chairs: " + (18 * 25));

Hint 3

The second is made the same way, with 60 * 60.

Terminal

Click Run to see what your program shows, then Submit answer to check it and unlock Next.