0

3 つのオブジェクトを作成した後、ユーザーから半径と高さを取得し、体積を計算してから、次の円柱を再度尋ねる必要があります。このコードを実行すると、半径と高さの入力を求められますが、体積は計算されません。私は何を間違っていますか?

import javax.swing.JOptionPane;
import java.io.*;


public class CylinderTest 
{
public static void main(String[] args) throws IOException
{
    String input;
    String input2;
    double radius[] = new double[3];
    double height[] = new double[3];
    Cylinder[] myCylinder = new Cylinder[3];



        for (int i = 0; i < myCylinder.length; i++)
        {

             input = JOptionPane.showInputDialog("Enter a radius");
                radius[ i ] = Double.parseDouble(input);
                input2 = JOptionPane.showInputDialog("Enter a height" +
                        "");


                height[i] = Double.parseDouble(input2);

                myCylinder[i].height = input2;
                myCylinder[i].radius = input;

                JOptionPane.showMessageDialog(null, " The volume of the cylinder is: " + myCylinder.getVolume());       
            }

    }







static class Cylinder
{
private double radius;
private double height;


public  Cylinder(double radius, double height)
     {      this.radius = radius;
            this.height = height;

}



public double getVolume()
{

    return radius * radius * height * Math.PI;


}
}

}
4

3 に答える 3

1

staticCylinder クラス内の変数とメソッドにキーワードを使用しています。staticキーワードを使用した理由はわかりませんが、プログラム全体でインスタンスが1 つstaticしかないことを暗示しています (つまり、グローバル変数または関数です)。これを修正するには、Cylinder クラスのメソッドとメンバー変数で static という単語を削除します。3.1416 を PI として使用する代わりに、 Math.PIを確認することもできます。

また、ボリュームを変数に格納する必要がないことにも言及したいと思います。代わりに、単に返品することができます。もちろん、何らかの理由で変数にキャッシュしたい場合を除きますが、を呼び出すたびに再計算しているため、getVolume()変数にボリュームを格納する必要はありません。

すなわち

public double getVolume() // notice: no static keyword in the method's prototype
{
    return (radius * radius) * height * Math.PI;
}

プロのヒント:コードでマジック ナンバーを使用しないでください。変数を使用してマジック ナンバーを格納します。定数 (最終) 変数または通常の変数として。

例えば

 static final int MEANING_OF_LIFE = 42; // this is somewhere tucked in a class or method
                                        // static is used because the final keyword
                                        // is used and therefore isn't modified
                                        // Meaning that there is no real point to have
                                        // multiple MEANING_OF_LIFE variables, hence static

 // ...

 System.out.printf("The meaning of life is: %i", MEANING_OF_LIFE);
于 2013-01-26T01:24:51.233 に答える
0

あなたが忘れてしまった

 myCylinder[i].height = input2;
 myCylinder[i].radius = input;

プラス、

 JOptionPane.showMessageDialog(null, " The volume of the cylinder is: " + myCylinder.getVolume());
于 2013-01-26T01:24:35.347 に答える
0

staticgetVolume() からを削除します。フィールドボリューム、高さから静的を削除します。
計算するには、シリンダー オブジェクトを作成し、ボリュームを取得する必要があります。

Cylinder cyl = new Cylinder(radius, height);
double volume = cyl.getVolume();
于 2013-01-26T01:24:36.813 に答える