java—我需要能够使用for each循环在arraylist中找到最小的卷

sd2nnvve  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(424)

这是我到目前为止所做的代码。它创造了 ArrayList 加上圆圈。卷被存储并在控制台中打印。我要做的最后一件事就是用for each循环打印出最小的卷。这就是我遇到的困难。我真的需要一些帮助/建议

public static void main(String[] args)
{
    Random rand = new Random();
    final int RADIUS_MAX = 100;

    int NUM_SPHERES = 4;

    List<Sphere> spheres = new ArrayList<Sphere>();

    for(int add = 1; add <= NUM_SPHERES; add++) {
        spheres.add(new Sphere(rand.nextInt(RADIUS_MAX)));  
    }

    for (Sphere s : spheres) {
        System.out.println(s);      
    }

    //TODO: Convert to a for-each loop to find the volume of the smallest sphere
    for (Sphere s : spheres) {
    } 
}
46scxncf

46scxncf1#

这个 volume 球面的公式依赖于半径 V <=> R ,因此不需要每次都计算体积,因为最小凸面将具有最小半径。

public class Foo {

    public static void main(String... args) {
        Random rand = new Random();
        final int maxRadius = 100;
        final int totalSphere = 4;

        List<Sphere> spheres = new ArrayList<>();

        for (int i = 0; i < totalSphere; i++)
            spheres.add(new Sphere(rand.nextInt(maxRadius)));

        for (Sphere sphere : spheres)
            System.out.println(sphere);

        Sphere smallestSphere = spheres.get(0);

        for (Sphere sphere : spheres)
            if (smallestSphere == null || sphere.compareTo(smallestSphere) < 0)
                smallestSphere = sphere;

        System.out.println("smallest volume: " + smallestSphere.getVolume());
    }

    public static class Sphere implements Comparable<Sphere> {

        private final int radius;

        public Sphere(int radius) {
            this.radius = radius;
        }

        public double getVolume() {
            return (4. / 3) * Math.PI * Math.pow(radius, 3);
        }

        @Override
        public String toString() {
            return "radius: " + radius;
        }

        @Override
        public int compareTo(Sphere sphere) {
            return Integer.compare(radius, sphere.radius);
        }
    }

}
uxhixvfz

uxhixvfz2#

您不需要额外的循环。半径最小的球体体积最小。您可以存储到目前为止最小的卷(初始化为非常大的卷)并在现有循环中更新它。我相信体积的公式是 (4. / 3) * Math.PI * Math.pow(radius, 3) .

相关问题