【发布时间】:2018-02-27 19:25:58
【问题描述】:
我正在尝试完成一个 Java 实验室练习,该练习要求在数组中显示对象(圆柱体)的体积。每当我尝试打印数组时,输出似乎总是数组中的最后一个对象,而我希望它们都打印出来。
这是我的 Cylinder.java 代码:
public class Cylinder implements Comparable<Cylinder> {
public static double radius;
public static double height;
public static String name;
public Cylinder(double radius, double height, String name){
this.radius = radius;
this.height = height;
this.name = name;
}
@Override
public int compareTo(Cylinder obj) {
Cylinder other = obj;
int result;
if (this.volume() > other.volume()){
result = -1;
}
else if (this.volume() < other.volume()){
result = 1;
}
else {
result = 0;
}
return result;
}
public double volume(){
double volume = Math.pow(radius, 2.0)*Math.PI*height;
return volume;
}
public double surface(){
double surface = (4.0*Math.PI)*Math.pow(radius, 2.0);
return surface;
}
public String toString(){
return "Name: " + name + ", radius: " + radius + ", height: " + height ;
}
}
TestSolids.java,打印数组:
import java.util.Arrays;
public class TestSolids {
public static void testCylinderSort(Cylinder[] cylinders){
for(int i = 0; i < cylinders.length; i++){
double volume = cylinders[i].volume();
System.out.println("Volume of Cylinder " + (i+1) + " " + volume);
}
}
public static void main(String[] args){
final Cylinder[] CYLINDERS = { new Cylinder(10, 5, "one"), new Cylinder(5, 10, "two"), new Cylinder(7, 7, "three") };
System.out.println(Arrays.toString(CYLINDERS));
testCylinderSort(CYLINDERS);
}
}
我的输出:
[Name: three, radius: 7.0, height: 7.0, Name: three, radius: 7.0, height: 7.0, Name: three, radius: 7.0, height: 7.0]
Volume of Cylinder 1 1077.566280181299
Volume of Cylinder 2 1077.566280181299
Volume of Cylinder 3 1077.566280181299
输出显示我可以打印数组的不同索引,但由于某种原因,它们都引用了数组的最后一个元素,我不知道为什么会这样。如果有人能告诉我这里发生了什么以及如何打印所有数组对象,我将非常感激。
【问题讨论】:
-
从变量声明中删除
static -
啊!它总是那么简单,谢谢你的工作。为什么列出的是最后一个元素而不是第一个元素?
标签: java arrays object for-loop