Java Exercises: Compute the area of a polygon
Java Basic: Exercise-35 with Solution
Write a Java program to compute the area of a polygon.
Area of a polygon = (n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side.
Test Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Pictorial Presentation: Area of Polygon
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise35 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the number of sides on the polygon: ");
int ns = input.nextInt();
System.out.print("Input the length of one of the sides: ");
double side = input.nextDouble();
System.out.print("The area is: " + polygonArea(ns, side)+"\n");
}
public static double polygonArea(int ns, double side) {
return (ns * (side * side)) / (4.0 * Math.tan((Math.PI / ns)));
}
}
Sample Output:
Input the number of sides on the polygon: 7 Input the length of one of the sides: 6 The area is: 130.82084798405722
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to compute the area of a hexagon.
Next: Write a Java program to compute the distance between two points on the surface of earth.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework