Write a "proper" Polygon class, using "proper" class design. It needs to have: 1) The number of sides it has (an int) and it's x and y location (both floats) as private member variables. 2) Accessors and mutators for the member variables. (AKA getters/setters.) 3) Constructors to set the member variables when the class is initialized
Write a "proper" Polygon class, using "proper" class design. It needs to have:
1) The number of sides it has (an int) and it's x and y location (both floats) as private member variables.
2) Accessors and mutators for the member variables. (AKA getters/setters.)
3) Constructors to set the member variables when the class is initialized
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.Scanner;
class Point {
float x, y;
Point(float x, float y) {
this.x = x;
this.y = y;
}
}
class Polygon {
private Point[] points;
int sides;
Polygon(int sides, Point[] points) {
this.sides = sides;
this.points = points;
}
public void calculateDistanceBetweenSides() {
for (int i=0; i<sides; i++) {
int side1 = i%sides, side2 = (i+1)%sides;
double distance = distance(points[side1].x, points[side1].y, points[side2].x, points[side2].y);
System.out.println(String.format("Distance between points (%.2f, %.2f) and (%.2f, %.2f) = %.2f", points[side1].x
, points[side1].y, points[side2].x, points[side2].y, distance));
}
}
private double distance(float x1, float y1, float x2, float y2) {
return Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
}
public Point[] getPoints() {
return points;
}
public int getSides() {
return sides;
}
}
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of sides of the polygon.");
int sides = sc.nextInt();
Point[] points = new Point[sides];
for (int i=0; i<sides; i++) {
System.out.println(String.format("Enter x%d and y%d",(i+1),(i+1)));
points[i] = new Point(sc.nextInt(), sc.nextInt());
}
Polygon polygon = new Polygon(sides, points);
polygon.calculateDistanceBetweenSides();
}
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps