如何在Java中生成随机图像

时间:2016-01-19 15:54:11

标签: java arrays random

我正在创建一个骰子游戏,但我不确定如何随机生成图像,因此结果是随机的。什么是最好的方法,我听说数组会很好,但如果我有一个数组,我需要case语句。

/When pause completed message sent to callback
class Roll extends TimerTask {
    public void run() {
        handler.sendEmptyMessage(0);
    }
}

//Receives message from timer to start dice roll
Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        //Get roll result
        //Remember nextInt returns 0 to 5 for argument of 6
        //hence + 1
        switch(rng.nextInt(6)+1) {
        case 1:
            dice_picture.setImageResource(R.drawable.one);
            dice_picture2.setImageResource(R.drawable.five);
            break;
        case 2:
            dice_picture.setImageResource(R.drawable.two);
            dice_picture2.setImageResource(R.drawable.four);
            break;
        case 3:
            dice_picture.setImageResource(R.drawable.three);
            dice_picture2.setImageResource(R.drawable.five);
            break;
        case 4:
            dice_picture.setImageResource(R.drawable.four);
            dice_picture2.setImageResource(R.drawable.three);
            break;
        case 5:
            dice_picture.setImageResource(R.drawable.five);
            dice_picture2.setImageResource(R.drawable.two);
            break;
        case 6:
            dice_picture.setImageResource(R.drawable.six);
            dice_picture2.setImageResource(R.drawable.one);
            break;
        default:
        }
        rolling=false;  //user can press again
        return true;
    }
};

1 个答案:

答案 0 :(得分:3)

如果您声明一个(或两个)可绘制图像数组(假设R.drawable是正确类型),则您不需要case语句:

R.drawable[] dice= {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six};
R.drawable[] dice2= {R.drawable.five, R.drawable.four,...};

然后你可以写:

int randomNumber = rng.nextInt(6);
dice_picture.setImageResource(dice[randomNumber]);
dice_picture2.setImageResource(dice2[randomNumber]);

而不是您的开关代码。

根据要求提供了一个完整的工作示例,它返回一个随机文本:

import java.util.Random;

public class RandomText {

    String[] texts={"Hello", "World", "Cafe-Babe"};

    public static void main(String[] args){
        RandomText randText = new RandomText();
        randText.performRandom();
    }

    void performRandom(){
        Random rand = new Random();
        printText(texts[rand.nextInt(texts.length)]);
    }

    static void printText(String text){
        System.out.println(text);
    }
}