Java: A Rectangle class

Write your first class: data, a constructor and a few methods.

What to build

A Rectangle class used to describe several rectangles.

Requirements

  • Write a class Rectangle with private fields width and height, a constructor, area(), perimeter(), isSquare() and toString() returning Rectangle(WxH).
  • For each input line print Rectangle(WxH): area A, perimeter P and, for squares, (a square) at the end.

Input

Line 1: n. Then n lines W H.

Output

n lines.

Constraints

1 ≤ n ≤ 50; 1 ≤ W, H ≤ 10000.

Example

Input:

2
3 4
5 5

Output:

Rectangle(3x4): area 12, perimeter 14
Rectangle(5x5): area 25, perimeter 20 (a square)

Why it works

The rectangle's measurements live in one object, and each method answers a question about that object, so main reads like a description instead of a calculation.

Examples

Example 1 · Input
2
3 4
5 5
Expected output
Rectangle(3x4): area 12, perimeter 14
Rectangle(5x5): area 25, perimeter 20 (a square)
Example 2 · Input
1
1 10000
Expected output
Rectangle(1x10000): area 10000, perimeter 20002

Hints

Hint 1

Give Rectangle two private int fields and a constructor that sets them.

Hint 2

Override toString to return "Rectangle(WxH)".

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

class Rectangle {
    private final 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);
    }

    boolean isSquare() {
        return width == height;
    }

    @Override
    public String toString() {
        return "Rectangle(" + width + "x" + height + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            Rectangle r = new Rectangle(in.nextInt(), in.nextInt());
            System.out.println(r + ": area " + r.area() + ", perimeter " + r.perimeter() + (r.isSquare() ? " (a square)" : ""));
        }
    }
}

Lesson: Classes and objects →