【发布时间】:2019-09-29 17:44:39
【问题描述】:
我的老师给了我这个
- 在 n 边正多边形中,所有边的长度相同,所有角的度数相同。设计一个名为 RegularPolygon 的类,其中包含: 一个名为 n 的私有 int 数据字段,用于定义 Polygon 中的边数,默认值为 3。 一个名为 side 的私有双数据字段,存储边的长度,默认值为 1。 一个名为 X 的私有双精度数据字段,它定义了多边形中心的 x 坐标,默认值为 0。 一个名为 Y 的私有双精度数据字段,它定义了多边形中心的 y 坐标,默认值为 0。 一个构造函数,它创建具有指定边数、边长和 x - 和 y- 坐标的正多边形(值从参数传递到字段)。 所有数据字段的访问器方法。 getPerimeter() 方法返回多边形的周长。 getArea() 方法返回多边形的面积。公式为面积 = n * s*s / (4 * tan(PI / n))。
2) 编写一个RegularPolygonTest 类,允许用户输入数据字段,您的程序会打印出正多边形的周长和面积。
这是我目前的代码:
public class RegularPolygon{
private int n;
private double side, x, y;
public RegularPolygon(){
n = 3;
side = 1;
x = 0;
y = 0;
}
public RegularPolygon(int n, double side){
this.n = n;
this.side = side;
x = 0;
y = 0;
}
public RegularPolygon(int sn, double length, double x_coord, double y_coord){
n = sn;
side = length;
x = x_coord;
y = y_coord;
}
//set n to the user input
public void setN(int other){
n = other;
}
public int getN(){
return n;
}
//set side to userinput
public void setSide(double otherside){
side = otherside;
}
public double getSide(){
return side;
}
//set x to user input
public void setX(int x_co){
x = x_co;
}
public double getX(){
return x;
}
//set y to user input
public void setY(int they){
y = they;
}
public double getY(){
return y;
}
//find perimeter
public double getPerimeter(){
return n * side;
}
//find area
public double getArea(){
double s_squ = side * side;
double pin = Math.PI/n;
double tangent = Math.tan(pin);
return (n*s_squ)/(4*tangent);
}
}
import java.util.Scanner;
public class RegularPolygonTest{
public static void main(String[] args){
Scanner yer = new Scanner(System.in);
//number of sides
System.out.println("Enter number of sides: ");
int sn = yer.nextInt();
//length of sides
System.out.println("Enter length of sides: ");
double length = yer.nextDouble();
//x-coord
System.out.println("Enter the x-coordinate of the center: ");
double x_coord = yer.nextDouble();
//y-coord
System.out.println("Enter the y-coordinate of the center: ");
double y_coord = yer.nextDouble();
if (x_coord == 0 && y_coord == 0){
RegularPolygon rp = new RegularPolygon(sn, length);
}
else if (sn > 3 && length > 1){
RegularPolygon rp = new RegularPolygon(sn, length, x_coord, y_coord);
}
else{
RegularPolygon rp = new RegularPolygon();
}
System.out.println("The perimeter of the " + rp.getN() + "-sided polygon is : "+ rp.getPerimeter() +". And the are is : "+ rp.getArea());
}
}
我得到的错误是 IDE 找不到符号,它指向最后一行中的所有 rp。我该如何解决这个错误?
【问题讨论】:
标签: java