Java Arena
Step 5 of 6

A small calculator

Time to put the operators together. A calculator program reads two numbers and prints one line per operation:

Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
System.out.println(a + " + " + b + " = " + (a + b));
System.out.println(a + " / " + b + " = " + ((double) a / b));
Input
7
2
Output
7 + 2 = 9
7 / 2 = 3.5

Two details make it right:

  • Each calculation is in parentheses, so it happens before the joining.
  • The division casts to double, so 7 / 2 shows 3.5 and not 3.

Your task

Challenge 1 of 3

Read two whole numbers and print their sum and difference. For the input 8 and 3 the program prints:

8 + 3 = 11
8 - 3 = 5

Challenge 2

Now all four operations, with the division as a decimal number. For the input 9 and 2 the program prints:

9 + 2 = 11
9 - 2 = 7
9 * 2 = 18
9 / 2 = 4.5

Challenge 3

Add one more line: the first number as a percentage of the second, as a decimal number. For the input 5 and 20 the program prints:

5 + 20 = 25
5 - 20 = -15
5 * 20 = 100
5 / 20 = 0.25
5 is 25.0% of 20