6-49 设计RegularPolygon类分数 10
定义一个RegularPolygon类,表示正n边形。一个正n边形中,所有边的长度都相同,且所有角的度数都相同。RegularPolygon类包括:
- 一个名为n的int类型私有数据域,表示多边形边数,默认值为3。
- 一个名为side的double类型私有数据域,表示多边形边长,默认值为1。
- 一个名为x的double类型私有数据域,表示多边形中点的x坐标,默认值为0。
- 一个名为y的double类型私有数据域,表示多边形中点的y坐标,默认值为0。
- 无参构造方法。
- 指定边数和边长,中心在(0,0)的构造方法。
- 指定边数和边长,中心在(x,y)的构造方法。
- n、side、x和y的更改器和访问器方法。
- 成员方法getPerimeter,返回多边形周长。
- 成员方法getArea,返回多边形面积。求面积公式如下:
注意,RegularPolygon类的定义应该这样开始:
classRegularPolygon {
也就是说,RegularPolygon类的class前面不要有public。
裁判测试程序样例:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
RegularPolygon poly1 = new RegularPolygon();
System.out.printf("%.2f %.2f\n", poly1.getPerimeter(), poly1.getArea());
int n = in.nextInt();
double side = in.nextDouble();
RegularPolygon poly2 = new RegularPolygon(n, side);
System.out.printf("%.2f %.2f\n", poly2.getPerimeter(), poly2.getArea());
n = in.nextInt();
side = in.nextDouble();
double x = in.nextDouble();
double y = in.nextDouble();
RegularPolygon poly3 = new RegularPolygon(n, side, x, y);
System.out.printf("%.2f %.2f\n", poly3.getPerimeter(), poly3.getArea());
in.close();
}
}
/* 请在这里填写答案 */
class RegularPolygon {
//TODO 编写代码
}
输入样例:
6 4
10 4 5.6 7.8
输出样例:
3.00 0.43
24.00 41.57
40.00 123.11
以下是答案
import java.util.Scanner;
public class Pta_6_49_2 {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
RegularPolygon poly1 = new RegularPolygon();
System.out.printf("%.2f %.2f\n", poly1.getPerimeter(),poly1.getArea());
int n = in.nextInt();
double side = in.nextDouble();
RegularPolygon poly2 = new RegularPolygon(n,side);
System.out.printf("%.2f %.2f\n", poly2.getPerimeter(),poly2.getArea());
n = in.nextInt();
side = in.nextDouble();
double x = in.nextDouble();
double y = in.nextDouble();
RegularPolygon poly3 = new RegularPolygon(n,side,x,y);
System.out.printf("%.2f %.2f\n", poly3.getPerimeter(),poly3.getArea());
in.close();
}
}
//以下是答案
class RegularPolygon{
private int n = 3;
private double side = 1;
private double x = 0;
private double y = 0;
RegularPolygon(){
}
RegularPolygon(int n,double side){
this.n = n;
this.side = side;
}
RegularPolygon(int n,double side,double x,double y){
this.n = n;
this.side = side;
this.x = x;
this.y = y;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getPerimeter() {
return this.n*this.side;
}
public double getArea() {
return (n*side*side)/(4*Math.tan(Math.PI/n));
}
}