【发布时间】:2016-05-17 10:22:09
【问题描述】:
作业要求执行以下操作,但我无法获得除 0 以外的任何内容来显示面积或体积。我不知道这是继承问题还是数学问题(我想我正确地转换为 int ?) 任何帮助将不胜感激。
设计并实现三个不同的类,它们共同定义形状:圆形、圆锥和球体。对于每个类,存储有关其大小的基本数据,并提供访问和修改这些数据的方法。此外,请提供适当的方法来计算 Sphere 和 Cone 的面积和体积。
在您的设计中,请考虑形状之间的关系以及可以在何处实现继承。不要创建重复的实例变量。创建一个 main 方法,实例化 2 个 Sphere 对象(任何参数)、2 个 Cone 对象(任何参数),使用 ToString() 显示它们,更改每个参数(您的选择),然后再次显示它们。
Attached 是一个可选的基本文件,可帮助您在同一个文件中定义不同的类。请记住,您必须重命名基本文件和类以包含您的姓氏。
这是我的代码。作业要求我们将所有内容都提交到一个文件中,而每个班级需要单独的文件,这就是为什么它们都在同一个文件中。
public class Coughlin_A04Q1
{
public int radius;
public int height;
public int area;
public int volume;
public static void main(String[] args)
{
Cone cone1 = new Cone(10,20);
Cone cone2 = new Cone(5,10);
Sphere sphere1 = new Sphere(3);
Sphere sphere2 = new Sphere(5);
System.out.println(cone1);
System.out.println(cone2);
System.out.println(sphere1);
System.out.println(sphere2);
}
public static class Round extends Coughlin_A04Q1
{
private int volume()
{
return (int)(Math.PI * Math.pow(radius,2.0) * height);
}
private int area()
{
return (int)((2*Math.PI*radius*height) + (2*Math.PI*Math.pow(radius,2)));
}
public Round(int radius, int height)
{
this.radius = radius;
this.height = height;
}
}
/////////////////////////////////////// ////////////////////////////////////p>
public static class Cone extends Coughlin_A04Q1
{
public Cone(int radius, int height)
{
this.radius = radius;
this.height = height;
}
public int area()
{
return (int)(Math.PI*radius*(radius +
Math.sqrt(Math.pow(height,2.0)+Math.pow(height,2.0))));
}
public int volume()
{
return (int)(Math.PI*Math.pow(radius,2)*(height/3));
}
public String toString()
{
return "A Cone of radius: " +radius+ ", area: "+area+", and volume: "
+volume+".";
}
}
/////////////////////////////////////// /////////////////////////////////////////p>
public static class Sphere extends Coughlin_A04Q1
{
public Sphere(int radius)
{
this.radius=radius;
}
public int area()
{
return (int)(4*Math.PI*Math.pow(this.radius,2));
}
public int volume()
{
return (int)((4/3)*Math.PI*Math.pow(radius,3));
}
public String toString()
{
return "A Sphere of radius: " +radius+ ", area: "+ area +", and volume:
" +volume+".";
}
}
}
【问题讨论】:
-
您显示了很多代码,但没有结果。显示结果和任何错误消息。
-
对不起,这是输出。半径圆锥:10,面积:0,体积:0。半径圆锥:5,面积:0,体积:0。半径球体:3,面积:0,体积:0。球体半径:5,面积:0,体积:0。
-
int指的是整数。为什么不使用double或float来计算面积和体积?注意4/3是1... -
最大的问题是函数
ToString返回的是Coughlin_A04Q1类的成员area和volume的值,它们永远不会被修改,即使在函数area()和@中也是如此987654334@.
标签: java class inheritance math subclass