簡體   English   中英

如何創建循環來迭代對象並顯示數組中對象的計算?

[英]How do I create a loop to iterate objects and display calculations of the objects from the array?

我是 Java 的新手,目前正在做一個小項目來學習。 這些是項目的要求:

  1. 使用名為 radius 的字段創建名為 Circle 的 class。
  • 包含默認構造函數
  • 包括一個默認構造函數,默認將半徑設置為 1。
  • 包括另一個接收半徑並將半徑設置為接收到的值的構造函數。
  • 包括一個返回圓面積的方法。 - 包括另一種返回圓的周長的方法。
  • 使用數學 class 的 PI 常數進行此計算。
  1. 創建一個名為 TestCircle 的 class,其 main() 方法聲明了 5 個 Circle 對象並將它們存儲在一個數組中
  • 5 個圓形對象將具有不同的半徑值
  • 使用循環,迭代對象並顯示數組中對象的區域和周長
  • 如果半徑為 1,則顯示一條消息“這是一個單位圓”。

我盡力完成了一些要求,但我不知道如何

使用循環,迭代對象並顯示數組中對象的區域和周長。 如果半徑為 1,則顯示一條消息“這是一個單位圓”。

class Circle {
    double radius;
    //constructor to default radius to 1
    public Circle() {
        this.radius = 1;
    }
    //constructor to receive values and set it as radius
    public Circle(double [] circlesRad) {
        this.radius = circlesRad[0];
    }

    public double computeArea(){
        return Math.PI * (radius * radius);
    }

    public double computeCircumference() {
        return Math.PI *2*radius;   
    }
}


public class TestCircle {

    public static void main(String[] args) {
        Circle c1 = new Circle();
        double circlesRad[] = {1, 34, 56, 23, 93, 18};
    
        for (double rad : circlesRad) {
            System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
            if (rad == 1){
                System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
                System.out.println("This is a unit circle.");
            }
        }
    }
}

我知道這是非常錯誤的,我道歉。 任何幫助將非常感激。

以下是代碼:-


class Circle {
    double radius;
    //constructor to default radius to 1
    public Circle() {
        this.radius = 1;
    }
    //you should consider this as just passing a radius value.
    public Circle(double circlesRad) {
        this.radius = circlesRad;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public double computeArea(){
        return Math.PI * (radius * radius);
    }

    public double computeCircumference() {
        return Math.PI *2*radius;
    }
}


public class TestCircle {

    public static void main(String[] args) {
        Circle[] circles = {new Circle(1), new Circle(34), new Circle(56),
        new Circle(23), new Circle(93), new Circle(18)};

        for (Circle circle : circles) {
            System.out.println("Circle:"+"\nArea: "+ circle.computeArea()+"\nCircumference: "+ circle.computeCircumference());
            if (circle.getRadius() == 1){
                System.out.println("This is a unit circle.");
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM