gpt4 book ai didi

java - 是否可以在 while 循环中设置可变数量的条件?

转载 作者:行者123 更新时间:2023-11-30 00:47:05 28 4
gpt4 key购买 nike

我正在尝试将对象放置到屏幕上,并且在放置每个对象之后,我正在使用一个 while 循环来不断替换下一个对象,直到它不与任何先前的对象重叠,然后如果有尝试太多我就停在那里。

问题是while循环中的条件数量需要在每个对象放置后增加,所以我想知道是否有某种方法,类似于使用求和而不是加法?

编辑:

对于每个小于最大对象数的 i,所有这些代码都包含在另一个 for 循环中。我尝试引入您可以看到的 for 循环,但这只会一次检查对象是否与另一个对象相交,以便它可以与前一个对象重叠。

            if(i > 0) {
for (int j = i - 1; j >= 0; j--) {
while ((atomXPosition[i] < atomXPosition[j] + atomWidth[j]
&& atomXPosition[i] + atomWidth[i] > atomXPosition[j]
&& atomYPosition[i] + atomWidth[i] > atomYPosition[j]
&& atomYPosition[i] < atomYPosition[j] + atomWidth[j])) {
atomXPosition[i] = (float) Math.random() * (screenWidth - atomWidth[i]);
}
}
}

最佳答案

为什么不用 Atom 类?

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

public class Atom {

private static final int NUM_ATOMS = 20;
private static final int MAX_TRIES = 3;

public static void main(String[] args) {
List<Atom> atoms = new ArrayList<>();

for (int i = 0; i < NUM_ATOMS; i++) {
Atom atom = new Atom();

atoms.add(atom);

for (int tries = 0; tries < MAX_TRIES; tries++) {
if (atom.intersectsAny(atoms)) {
int randomX = //...
int randomY = //...
atom.moveTo(randomX, randomY);
}
}
}
}

private int x;
private int y;
private int width;
private int height;

public boolean intersectsAny(List<Atom> atoms) {
return atoms.stream().anyMatch(this::intersects);
}

private boolean intersects(Atom other) {
if (this == other) {
return false;
}

return //... check if this atom intersects other atom
}

public void moveTo(int x, int y) {
this.x = x;
this.y = y;
}
}

关于java - 是否可以在 while 循环中设置可变数量的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41621307/

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