Challenge: Rectangle Class
Completed
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
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
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