gpt4 book ai didi

java - Java中的"new way for loop",不起作用,建议吗?

转载 作者:行者123 更新时间:2023-12-01 16:57:34 24 4
gpt4 key购买 nike

这是我的问题:我试图使用java中新的for循环来打印一些带有 double 的字符串。当我编译代码时,没有错误,但没有输出,就像 for 循环不起作用一样,有什么帮助吗?

循环就在最后,为了确定起见,我打印了所有代码。

abstract class Figure3D {

private float[] center;

protected void setCenter(float[] center){this.center = center;}

public abstract double calcolateVolumn();

protected abstract String figureType();

public void printVolumn(){
System.out.println("Volumn "+ figureType() + calcolateVolumn());
}

}


class Cube extends Figure3D{

private float side;

public Cube(float side, float[] center){
this.side = side;
setCenter(center);
}

@Override
protected String figureType(){
return "Cube ";
}

@Override
public double calcolateVolumn(){
return side*side*side;
}

}

class Sphere extends Figure3D {

private float radius;

public Sphere(float radius, float[] center){
this.radius = radius;
setCenter(center);
}

protected String figureType(){return "Sphere ";}

public double calcolateVolumn(){return ((4f/3f)*radius*radius*radius*3.14f);}

}

import java.util.ArrayList;
import java.util.List;

class TridimensionalFigures {
public static void main(String[] args) {
List<Figure3D> figures3d = new ArrayList<>(10);
Sphere sphere;
Cube cube;

for (int i = 0; i < figures3d.size(); i++) {
sphere = new Sphere(i, new float[] {i, i, i});
figures3d.add(i, sphere);
i++;
cube = new Cube(i, new float[] {i, i, i});
}

//TOFIX: it needs to print out the volums of all the objects in the arraylist
for (Figure3D figures : figures3d) {
System.out.printf("The volumns is: %s %n", figures.calcolateVolumn());
}
}
}

最佳答案

figures3d.size() 为 0,因此您没有向列表中添加任何内容。

尝试改变

for (int i = 0; i < figures3d.size(); i++) {

for (int i = 0; i < 10; i++) {

关于java - Java中的"new way for loop",不起作用,建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30549623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com