Constructor Overloading
Completed
Create Rectangle with constructors Rectangle() (1×1), Rectangle(int side) (square) and Rectangle(int w, int h), chained with this(...). Read lines with 0, 1 or 2 numbers and print WxH area=A.
Input
n, then n lines (a line may be - for no numbers).
Output
n lines.
Example
Input
3 - 4 2 7
Output
1x1 area=1 4x4 area=16 2x7 area=14
Editor
Java
Hints
this(...) calls another constructor of the same class and must be the first statement.
Solution explanation
Chaining constructors keeps the real initialisation in one place.
Show solution
import java.util.Scanner;
class Rectangle {
final int w, h;
Rectangle() {
this(1);
}
Rectangle(int side) {
this(side, side);
}
Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
@Override
public String toString() {
return w + "x" + h + " area=" + (w * h);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().trim());
for (int i = 0; i < n; i++) {
String line = sc.nextLine().trim();
String[] p = line.split("\\s+");
Rectangle r;
if (line.equals("-")) {
r = new Rectangle();
} else if (p.length == 1) {
r = new Rectangle(Integer.parseInt(p[0]));
} else {
r = new Rectangle(Integer.parseInt(p[0]), Integer.parseInt(p[1]));
}
System.out.println(r);
}
}
}