0

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

1 回答 1

0

What happens if all four colors are chosen?

Regardless, this doesn't seem to be a situation where a recursive call is required. Try something like the following:

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;
       }
    }
于 2012-04-10T03:02:07.790 回答