Challenge: Rectangle Class

Lab Java Beginner 10 points

Write a class Rectangle with fields width and height, a constructor, and methods area() and perimeter(). Read the width and height, create a rectangle and print:

Area: <area>
Perimeter: <perimeter>

Input

Two whole numbers: width and height.

Output

The two lines above.

Example

Input

4 3

Output

Area: 12
Perimeter: 14
Sample input available Sample output available
Editor
Java

Hints

Write class Rectangle above public class Main, without the word public.

The constructor uses this.width = width;

Solution explanation

The object keeps its own width and height, and its methods use them to calculate.

Show solution
import java.util.Scanner;

class Rectangle {
    int width, height;

    Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    int area() {
        return width * height;
    }

    int perimeter() {
        return 2 * (width + height);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Rectangle r = new Rectangle(sc.nextInt(), sc.nextInt());
        System.out.println("Area: " + r.area());
        System.out.println("Perimeter: " + r.perimeter());
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD