私はこれをいくつかの異なる方法で試しました。これらのクラスを拡張するには、継承を使用する必要があります。プログラムを実行するたびに、ボリュームと面積に0.0が出力されます。半径が正しく表示されます。下部に出力します。
public class Base_HW04Q1
{
public double pi = 3.14, l, radius, height, area, volume;
public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
area = (radius * radius) * pi;
return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + area + ".";
}
}
public static class Cylinder extends Base_HW04Q1
{
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = 2 * pi * radius * height + 2 * pi * l;
return area;
}
public double calcVolume() {
volume = pi * (radius * radius) * height;
return volume;
}
public String toString() {
return "A Cylinder of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}
public static class Cone extends Base_HW04Q1 //TODO: This line is almost, but not quite, complete.
{
public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = (pi * radius * l) + (pi * radius * radius);
return area;
}
public double calcVolume() {
volume = 0.333 * pi * radius * radius * height;
return volume;
}
public String toString() {
return "A Cone of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}
public static void main(String[] args)
{
//object creation
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);
//print for objects
System.out.println(Cylinder1);
System.out.println(RoundShape1);
System.out.println(Cone1);
}
}
出力:
半径の円柱:30.0、面積0.0、体積0.0半径の丸い形状:50.0、面積0.0。半径の円錐:10.0、面積0.0、体積0.0
あなたはtoString()
決して計算を行うメソッドを呼び出していないし、代わりにデフォルトの0.0フィールド値を出力します。メソッドが呼び出さtoString()
れる前calcXxxx()
、つまり計算フィールドに適切な値が与えられる前にが呼び出された場合、このリスクが発生します。最善の解決策は、面積や体積などの計算値のフィールドを完全に取り除くことによって、この問題が最初に発生するのを防ぐことです。代わりに、toString()内で、メソッドを呼び出してこれらの値を取得します。
例えば、
public double pi = 3.14, l, radius, height; // , area, volume;
public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
return (radius * radius) * pi;
// return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + calcArea() + ".";
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加