【问题标题】:Is it possible to have a variable number of conditions in a while loop?在while循环中是否可以有可变数量的条件?
【发布时间】:2017-01-12 19:24:22
【问题描述】:

我正在尝试将对象放置到屏幕上,并且在放置每个对象后,我正在使用 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]);
                    }
                }
            }

【问题讨论】:

  • 很难想象这一点。你能告诉我们你目前拥有的一些代码吗
  • while 循环的条件似乎并不统一。目前尚不清楚您要达到的目标。
  • while循环中的所有条件都需要为j在0和已经放置的对象数之间重复

标签: java android loops for-loop while-loop


【解决方案1】:

为什么没有 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;
    }
}

【讨论】:

    【解决方案2】:

    您可以在while 循环中使用函数作为条件。此函数可以将ArrayList 之类的内容作为输入,并且您可以在while 循环的每次迭代中将该对象添加到ArrayList

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多