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

时间:2012-04-10 01:29:20

标签: android random

我正在开发一个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);
    }

1 个答案:

答案 0 :(得分:0)

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

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

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;
       }
    }