Java Arena
Step 4 of 4

Combining the patterns

Bigger programs combine the patterns: read several values, calculate from them, decide, and print a sentence that uses the results. Here are two prices, and the program says which is cheaper and by how much:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int shopA = Integer.valueOf(scanner.nextLine());
        int shopB = Integer.valueOf(scanner.nextLine());
        int difference = Math.abs(shopA - shopB);
        if (shopA < shopB) {
            System.out.println("Shop A is cheaper by " + difference);
        } else if (shopB < shopA) {
            System.out.println("Shop B is cheaper by " + difference);
        } else {
            System.out.println("Same price");
        }
    }
}
Input
35
29
Output
Shop B is cheaper by 6

The difference is worked out once, before the decision, and each branch uses it. The same plan works for most problems of this kind: read everything, calculate what the sentences need, then decide which sentence to print.

Your task

Challenge 1 of 3

Read the heights of two plants in centimetres. Print The first plant is taller by X cm, The second plant is taller by X cm or The plants are equally tall. For the input 30 and 25 the program prints:

The first plant is taller by 5 cm

Challenge 2

Read the prices of two items and then how much money you have. Print You can buy both when the money covers both, and otherwise You need X more. For the input 12, 15 and 20 the program prints:

You need 7 more

Challenge 3

Alex and Sam each took two tests. Read Alex's two scores, then Sam's two, and print both averages and who has the higher one (or Same average). For the input 80, 90, 85 and 86 the program prints:

Alex: 85.0
Sam: 85.5
Sam has the higher average