Introduce Java How To Get the Area of a Rectangle and give examples
In Java, calculating the area of a rectangle is a straightforward task that involves using the formula:
[ \text{Area} = \text{length} \times \text{width} ]
To implement this in Java, you can create a simple program that prompts the user for the length and width of the rectangle, calculates the area, and then displays the result.
Here’s a basic example of how to get the area of a rectangle in Java:
import java.util.Scanner;
public class RectangleArea {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for the length and width
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
// Calculate the area
double area = length * width;
// Display the result
System.out.println("The area of the rectangle is: " + area);
// Close the scanner
scanner.close();
}
}
Importing Scanner: The Scanner
class is imported from the java.util
package to read user input.
Creating the Scanner Object: An instance of Scanner
is created to read input from the console.
User Input: The program prompts the user to enter the length and width of the rectangle. The nextDouble()
method is used to read the input as a double.
Calculating the Area: The area is calculated by multiplying the length and width.
Displaying the Result: The calculated area is printed to the console.
Closing the Scanner: The scanner.close()
method is called to close the scanner and free up resources.
If you run the program and input the length as 5
and the width as 3
, the output will be:
Enter the length of the rectangle: 5
Enter the width of the rectangle: 3
The area of the rectangle is: 15.0
Rectangle
class with methods to calculate the area, which would be a more object-oriented approach.Here’s how you could implement it using a class:
class Rectangle {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Method to calculate area
public double getArea() {
return length * width;
}
}
public class RectangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
// Create a Rectangle object
Rectangle rectangle = new Rectangle(length, width);
// Display the area
System.out.println("The area of the rectangle is: " + rectangle.getArea());
scanner.close();
}
}
This version encapsulates the rectangle's properties and behavior within a class, promoting better organization and reusability of code.