The following code snippet helps you to find the areas by providing the option to select that you find the area of your choice.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Areas {
public static void main(String args[]) throws Exception
{
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("1-Area of rectangle");
System.out.println("2-Area of circle");
System.out.println("3-Area of triangle");
System.out.println();
System.out.print("Select any option: ");
int select = Integer.parseInt( in .readLine());
switch (select)
{
case 1:
int width = 0;
int length = 0;
try
{
//read the length value
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
System.out.print("Please enter length of a rectangle: ");
length = Integer.parseInt(br.readLine());
//read the width value
System.out.print("Please enter width of a rectangle: ");
width = Integer.parseInt(br.readLine());
}
//if entered value is invalid
catch (NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
} catch (IOException ioe)
{
System.out.println("I/O Error :" + ioe);
System.exit(0);
}
int Rectarea = length * width; //by replacing 2(length+width) you get the perimeter of rectangle
System.out.println("Area of a rectangle is:" + Rectarea);
break;
case 2:
int radius = 0;
System.out.print("Please enter radius of a circle: ");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
radius = Integer.parseInt(br.readLine());
} catch (NumberFormatException ne)
{
System.out.println("Invalid radius value" + ne);
System.exit(0);
} catch (IOException ioe) {
System.out.println("IO Error :" + ioe);
System.exit(0);
}
double Circlearea = Math.PI * radius * radius; //by replacing (2*Math.PI*radius) you get the circumference of circle
System.out.println("Area of a circle is:" + Circlearea);
break;
case 3:
int base = 0;
int height = 0;
double half = 0.5;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
System.out.print("Please enter length of a rectangle: ");
length = Integer.parseInt(br.readLine());
System.out.print("Please enter width of a rectangle: ");
width = Integer.parseInt(br.readLine());
}
catch (NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch (IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
double Triarea = Math.abs(half) * base * height;
System.out.println("Area of a rectangle is:" + Triarea);
break;
default:
System.out.println("Wrong choice");
}
} catch (IOException e)
{
System.out.println("main method:" + e);
}
}
}Thank you, keep learning and sharing
