Read two numbers and print measurements of a rectangle, formatting the decimal result with printf.
What to build
A program that prints a rectangle's area, perimeter and diagonal.
Requirements
- Read the width and the height, whole numbers on one line.
- Print
Area: A,Perimeter: PandDiagonal: D, with D to two decimal places.
Input
One line: the width and the height.
Output
Three lines.
Constraints
1 ≤ width, height ≤ 10000.
Example
Input:
3 4
Output:
Area: 12
Perimeter: 14
Diagonal: 5.00
Why it works
Area and perimeter are whole numbers, so int arithmetic is exact, while the diagonal needs a square root, which is a double and is rounded only when printed.
Examples
Example 1 · Input
3 4
Expected output
Area: 12 Perimeter: 14 Diagonal: 5.00
Example 2 · Input
1 1
Expected output
Area: 1 Perimeter: 4 Diagonal: 1.41
Hints
Hint 1
nextInt() reads each number; Math.sqrt gives a square root.
Hint 2
printf("%.2f%n", value) prints two decimals.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int w = in.nextInt();
int h = in.nextInt();
System.out.println("Area: " + w * h);
System.out.println("Perimeter: " + 2 * (w + h));
System.out.printf("Diagonal: %.2f%n", Math.sqrt(w * w + h * h));
}
}