Challenge: Rectangle Calculator
Completed
Read the width and height of a rectangle (whole numbers) and print its area and perimeter.
Input
Two whole numbers: width and height.
Output
Area: <width × height> Perimeter: <2 × (width + height)>
Example
Input
4 3
Output
Area: 12 Perimeter: 14
Editor
Java
Hints
Read two numbers with sc.nextInt().
Put the maths in brackets when you join it to text: "Area: " + (w * h).
Solution explanation
Without brackets, "Area: " + w * h still works because * goes first, but "P: " + 2 * (w + h) is clearer with brackets around the whole sum.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
int h = sc.nextInt();
System.out.println("Area: " + (w * h));
System.out.println("Perimeter: " + (2 * (w + h)));
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module