这道题难点不在Circle类,Circle类怎么写 题干都说完了,get和tostring方法建议使用Eclipse或者Idea的自动生成

class Circle{
        private int radius;
        public Circle(){
            this.radius=2;
            System.out.println("this is a constructor");
        }
        public  Circle(int radius){
            this.radius=radius;
            System.out.println("this is a constructor with para");
        }
        public void setter(int radius){
            if(radius<=0)
                this.radius=2;
            else
                this.radius=radius;
        }
        public int getter(){
            return radius;
        }
        public int gerArea(){
            return (int)(Math.PI*radius*radius);
        }
        public String toString(){
            return "Circle [radius=" + radius + "]";
        }
}

这道题难点在Main类,写Main类的时候,注意在(4)才开始输入第一个数值,在没输入前程序就已经输出了

this is a constructor
Circle [radius=2]
c1:area=12
this is a constructor
Circle [radius=2]

根据样例输出得到每一行是由什么方法输出的

this is a constructor     //创建C1对象
Circle [radius=2]         //C1.tostring  
c1:area=12                //C1.getArea
this is a constructor     //创建C2对象
Circle [radius=2]         //C2.tostring
Circle [radius=4]         //接收半径,并用setter赋值后,再C2.tostring
c2:area=50                //C2.getArea
this is a constructor with para  //接收半径后,使用有参构造创建C3对象
Circle [radius=5]         //C3.tostring
c3:area=78                //C3.getArea

然后写出Main类代码如下,如果不能看出来,就写一行,测试一下,与样例对比差什么东西

public class Main {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int radius=input.nextInt();
        Circle c1=new Circle();
        System.out.println(c1.toString());
        System.out.println("c1:area="+c1.gerArea());
        Circle c2=new Circle();
        System.out.println(c2.toString());
        c2.setter(radius);
        System.out.println(c2.toString());
        System.out.println("c2:area="+c2.gerArea());
        radius=input.nextInt();
        Circle c3=new Circle(radius);
        System.out.println(c3.toString());
        System.out.println("c3:area="+c3.gerArea());
    }
}

仅供参考,如有更优解,可在评论区参与讨论

届ける言葉を今は育ててる
最后更新于 2022-04-05