How to find area and perimeter in Java.

This program finds the area or perimeter of selected shapes(triangle,circle,square  and rectangle).

Formulas used :-

Area
Circle= pi*r*radius.
Triangle=1/2*(base*height).
Square=side*side.
Rectangle=length*breadth.

Perimeter
Circle=2*pi*radius.
Triangle=a+b+c.
Square=4*side.
Rectangle=2*(length*breadth).

Java Code for above program -:

import java.util.Scanner;
public class area_perimeter {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println(“1.Area”);
System.out.println(“2.Perimeter”);
System.out.println(“Choose any one option:”);
int ch=s.nextInt();
if(ch<1||ch>2)
System.out.println(“Wrong option”);
else
System.out.println(“1.Triangle”);
System.out.println(“2.Circle”);
System.out.println(“3.Square”);
System.out.println(“4.Rectangle”);
System.out.println(“Enter your choice=”);
int r=s.nextInt();
switch(ch)
{
default:
System.out.println(“Choice is wrong”);
case 1:
{
switch(r)
{
default:
System.out.println(“Choice is wrong”);
case 1:
{
System.out.print(“Enter height and base of triangle”);
int height=s.nextInt(),base=s.nextInt();
double area=0.5*height*base;
System.out.println(“Area of triangle=”+area);
break;
}
case 2:
{
System.out.println(“Enter radius of circle”);
int radius=s.nextInt();
int area=(int)Math.PI*radius*radius;
System.out.println(“Area of circle=”+area);
break;
}
case 3:
{
System.out.println(“Enter side”);
int side=s.nextInt();
int area=side*side;
System.out.println(“Area of square=”+area);
break;
}
case 4:
{
System.out.println(“Enter length and breadth”);
int length=s.nextInt(),breadth=s.nextInt();
int area=length*breadth;
System.out.println(“Area of rectangle=”+area);
break;
}
}
break;
}
case 2:
{switch(r)
{
default:
System.out.println(“Choice is wrong”);
case 1:
{
System.out.print(“Enter three sides of triangle”);
int a=s.nextInt(),b=s.nextInt(),c=s.nextInt();
int perimeter=a+b+c;
System.out.println(“Perimeter of triangle=”+perimeter);
break;
}
case 2:
{
System.out.println(“Enter radius of circle”);
int radius=s.nextInt();
double perimeter=2*(int)Math.PI*radius;
System.out.println(“Perimeter of circle=”+perimeter);
break;
}
case 3:
{
System.out.println(“Enter side”);
int side=s.nextInt();
int perimeter=4*side;
System.out.println(“Perimeter of square=”+perimeter);
break;
}
case 4:
{
System.out.println(“Enter length and breadth”);
int length=s.nextInt(),breadth=s.nextInt();
int perimeter=2*(length+breadth);
System.out.println(“Perimeter of rectangle=”+perimeter);
break;
}
}
}
}
}
}

 

Output-:

 

Leave a Reply