How to calculate Rectangle Area using Java
The previous post, javawe were able to calculate circle are using Java .Today we are going to calculate rectangle area.
Calculating rectangle are code
[
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalculateRectangleArea {
public static void main(String args[])
{
int area=CalculateRectangleArea();
System.out.println("Rectangle Area is"+area);
}
public static int CalculateRectangleArea()
{
int w=0;
int l=0;
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter Rectangle Width");
w=Integer.parseInt(reader.readLine());
System.out.println("Please enter Rectangle length");
l=Integer.parseInt(reader.readLine());
}
catch(NumberFormatException ne)
{
System.out.println("Inavalid number entered"+ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("Inavalid number entered"+ioe);
System.exit(0);
}
int area=l*w;
return area;
}
}
]
Code Explanation:
There are some key points to note with above program.
I have used [public static int CalculateRectangleArea()] to calculate and return rectangle area.int is the return type.if a method is declared void,it means the method will not return anything.
The method is declared static because it has to be used in a static context.
Exceptions errors occurs incase user enters invalid numbers.Its wise to catch exceptions in your program to ensure runs well.In advanced java programs,notifications are made using [JOptionPane.showMessageDialog()]
See also
See also