Find Area of a Rectangle in Java
The formula for finding the area of a rectangle is,
area = length * width
Calculate Area of a Rectangle in Java
The following program calculates area of a rectangle in Java. The program asks the user for length and width values and then outputs the result in the console. We use BufferedReader to read a line of string and then use the parseDouble method of the Double class to convert the string to a number.
This program also illustrates the decorator pattern. We first decorate the console input stream (System.in) with a InputStreamReader and then again decorate it with BufferedReader. BufferedReader enables us to read a line of data from an input stream.
// Java program to find area of a rectangle import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RectangleArea { public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter length of the rectangle : "); double length = Double.parseDouble(reader.readLine()); System.out.print("Please enter width of the rectangle : "); double width = Double.parseDouble(reader.readLine()); System.out.println("Area of the rectangle : "+length*width); } }