0
public class circle
{

    double circle1;

    double Xvalue;

    double Yvalue;

    double radius;

    public double area = (3.14*(this.radius * this.radius));

    public double getArea ()
    {
        return area;




    }

}

//これは、オブジェクトを作成する 2 番目のクラスです

public class tester
{
   public static void main(String args [])

   {

        circle circle1 = new circle();

        circle1.Xvalue = 1;

        circle1.Yvalue = 2;

        circle1.radius = 4;

        System.out.println(getArea());


        //im not too sure why the print statement won't print the method getArea. 

    }
}
4

1 に答える 1

0

が必要ですSystem.out.println(circle1.getArea());。それ以外の場合は、そのようなメソッドを持たない Tester クラスで getArea() というメソッドを見つけようとしています。

また、コードは常に 0 の領域を返します。これは、データの初期化方法によるものです。

新しい円オブジェクトを作成すると、xValue が作成されます。これはプリミティブ型 (Double ではなく double) であるため、デフォルトで 0 の値が与えられます (何らかの値が必要なため)。

したがって、その時点で領域変数を定義する場所に到達すると (まだオブジェクトを作成しているため、(area = 3.14*(0.0 * 0.0)) になり、0 になります。

あなたが本当に欲しいのは、次のようなものです:

public class Circle {

    double Xvalue;

    double Yvalue;

    double radius;

    public Circle(double xValue, double yValue, double radius) {
        this.xValue = xValue;
        this.yValue = yValue;
        this.radius = radius;
    }

    public double getArea ()
    {
        return 3.1415926*(this.radius * this.radius);
    }
}

public class Tester
{
   public static void main(String[] args)

   {

        Circle circle1 = new Circle(1, 2, 4);

        System.out.println(circle1.getArea());


        //im not too sure why the print statement won't print the method getArea. 

    }
}
于 2013-04-17T21:03:23.790 に答える