Java Arena
Step 1 of 4

Read, calculate, print

Many programs have the same three parts, whatever they're about:

  1. Read the input into variables.
  2. Calculate the result from them.
  3. Print the result.

Here the input is a temperature in Celsius, and the result is the same temperature in Fahrenheit:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 1. Read
        int celsius = Integer.valueOf(scanner.nextLine());
        // 2. Calculate
        double fahrenheit = celsius * 9 / 5.0 + 32;
        // 3. Print
        System.out.println(celsius + " C is " + fahrenheit + " F");
    }
}
Input
25
Output
25 C is 77.0 F

When a new problem looks hard, start by naming the three parts: what does the program get, what does it work out, and what does it show? Each part is often just a line or two.

Keeping the calculation in its own variable (fahrenheit) makes the print line short and gives the result a name.

Your task

Challenge 1 of 3

Read the side of a square garden in metres and print its area. For the input 7 the program prints:

Area: 49

Challenge 2

Read the width and then the height of a rectangle, and print its area and its perimeter (the length of all four sides together). For the input 4 and 3 the program prints:

Area: 12
Perimeter: 14

Challenge 3

Read a length of time in minutes and print it in hours and minutes. For the input 135 the program prints:

2 h 15 min