Java Programming | Perimeter of shapes

Introduction

This is a tutorial for perimeter of shapes in java. The program calculates perimeter and prints it. The program is extendable. Go enjoy the program. Lets begin……….

Program for perimeter of circle in java.


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Perimeter {
//void main
public static void main (String[] args)
{
//declare float
float r,peri;
//print message
System.out.println("Enter radius of circle:");
//Take input
Scanner input = new Scanner(System.in);
r = input.nextFloat();
//calculate
peri = 2*3.142f*r;
//print the perimeter
System.out.println("Perimeter = "+peri);
}
}

Output

Enter radius of circle:
2
Perimeter = 12.568

Program for perimeter of rectangle in java.

[code language=”java”]
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Perimeter {
//void main
public static void main (String[] args)
{
//declare float
float a,b,peri;
//print message
System.out.println(“Enter length and breadth of rectangle:”);
//Take input
Scanner input = new Scanner(System.in);
a = input.nextFloat();
b = input.nextFloat();
//calculate
peri = (a+b)*2;
//print the perimeter
System.out.println(“Perimeter = “+peri);
}
}
[/code]

Output

Enter length and breadth of rectangle:
2
1
Perimeter = 6.0

How it works

  1. The program prints the message to enter required inputs.
  2. The user enters inputs.
  3. Perimeter is calculated
  4. The perimeter is printed.

Extending it

The program can be extended by using more different shapes of geometry. You can take the necessary inputs and calculate the perimeter of the given geometry.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter required inputs.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variable.
  7. Calculate perimeter and save it in other variable.
  8. Add system.out.println() function to print the calculated perimeter.

At the end.

You learnt creating the Java program for Perimeter of different shapes . So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: