Android 如果颜色仍然可用,则随机生成下一种颜色

Android 如果颜色仍然可用,则随机生成下一种颜色,android,random,Android,Random,我正在为android开发一款应用程序,在某些方面我很挣扎。其中之一是选择下一种颜色(四种颜色中的一种),但请记住,所选颜色可能已经是空的,在这种情况下,应选择四种颜色中的下一种 我有两种方法,但其中一种是太多的代码,另一种是导致崩溃(我猜这种情况会发生,因为它可能会以无休止的循环结束) 提前谢谢 public void nextColor(Canvas canvas) { Random rnd = new Random(System.currentTimeMillis());

我正在为android开发一款应用程序,在某些方面我很挣扎。其中之一是选择下一种颜色(四种颜色中的一种),但请记住,所选颜色可能已经是空的,在这种情况下,应选择四种颜色中的下一种

我有两种方法,但其中一种是太多的代码,另一种是导致崩溃(我猜这种情况会发生,因为它可能会以无休止的循环结束)

提前谢谢

public void nextColor(Canvas canvas) {
    Random rnd = new Random(System.currentTimeMillis());
    int theNextColor = rnd.nextInt(4);
    switch (theNextColor) {
    case 0:
        if (!blue.isEmpty()) {
            currentPaint = paintBlue;
        } else
            nextColor(canvas);

    case 1:
        if (!grey.isEmpty()) {
            currentPaint = paintGray;
        } else
            nextColor(canvas);
    case 2:
        if (!gold.isEmpty()) {
            currentPaint = paintGold;
        } else
            nextColor(canvas);
    case 3:
        if (!red.isEmpty()) {
            currentPaint = paintRed;
        } else
            nextColor(canvas);
    }

如果选择了所有四种颜色,会发生什么

无论如何,这似乎不是需要递归调用的情况。请尝试以下操作:

public void nextColor(Canvas canvas) {
    Random rnd = new Random(System.currentTimeMillis());
    int theNextColor;
    boolean colorFound = false;

    while (!colorFound) {
       theNextColor = rnd.nextInt(4);
       if (theNextColor == 0) {
         currentPaint = paintBlue;
         colorFound = true;
       } else if (theNextColor == 1) {
         currentPaint = paintGray;
         colorFound = true;
       } else if (theNextColor == 2) {
         currentPaint = paintGold;
         colorFound = true;
       } else if (theNextColor == 3) {
         currentPaint = paintRed;
         colorFound = true;
       }
    }

当它崩溃时,发布logcat显示的内容。您没有显示足够的代码,任何人都无法提供帮助。您好。谢谢你的回答。现在我很难找到调用此方法的正确位置。如果我在onDraw()方法上调用它,那么每次画布刷新时(每秒几次)颜色都会发生变化。您到底想在什么时候选择新颜色?你不是很具体…我用完全不同的方法解决了它。我创建了两个数组,一个包含对象,另一个包含适合对象颜色的数字。这样,只有我的对象具有的颜色才能选择为下一种颜色。