Java 我需要能够使用for-each循环找到ArrayList中的最小卷
这是我到目前为止所做的代码。它创建Java 我需要能够使用for-each循环找到ArrayList中的最小卷,java,arrays,volume,Java,Arrays,Volume,这是我到目前为止所做的代码。它创建ArrayList,并添加圆。该卷在控制台中存储和打印。我要做的最后一件事是使用for each循环打印出最小的卷。这就是我遇到困难的地方。我真的需要一些帮助/建议 public static void main(String[] args) { Random rand = new Random(); final int RADIUS_MAX = 100; int NUM_SPHERES = 4;
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) {
}
}
publicstaticvoidmain(字符串[]args)
{
Random rand=新的Random();
最终整数半径_MAX=100;
int NUM_球体=4;
列表球体=新的ArrayList();
对于(int add=1;add您不需要额外的循环。具有最小半径的球体将具有最小的体积。您可以存储迄今为止最小的体积(初始化为非常大的体积),并在现有的任一循环中更新它。我相信体积的公式是(4./3)*Math.PI*Math.pow(radius,3)
球体的体积
公式取决于半径,如vr
,因此无需每次计算体积,因为最小体积将与最小半径一起计算
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);
}
}
}
公共类Foo{
公共静态void main(字符串…参数){
Random rand=新的Random();
最终整数最大半径=100;
最终整数totalSphere=4;
列表球体=新的ArrayList();
对于(int i=0;i
您好,欢迎光临。您能给出球体的定义(代码)吗?我推荐这种方法。它将为您节省大量处理能力。