我有3张图片,我想在其中生成随机数。有一个数字数组,最小值为0,最大值为9.随机数生成一次但不再生成。
...代码
int r;
int min_ran=0;
int max_ran=9;
random.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
r = ran.nextInt(max_ran - min_ran + 1) + min_ran;
img1.setImageResource(images[image1+1]);
img2.setImageResource(images[image1-1]);
img3.setImageResource(images[(image1+1)*1]);
}
});
请帮忙
答案 0 :(得分:0)
使用此选项随机选择3张图像(范围从0到9)
random.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
img1.setImageResource(images[ran.nextInt(10)]);
img2.setImageResource(images[ran.nextInt(10)]);
img3.setImageResource(images[ran.nextInt(10)]);
}
}
答案 1 :(得分:0)
我想您想为3幅图像设置3种不同的图像资源,并从名为images[]
的图像资源数组中选择它们。要随机选择3个彼此不同的图像,您可以执行以下操作:
private Random randomGenerator = new Random();
random.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int firstIndex = randomGenerator.nextInt(10);
int secondIndex = newDifferentRandomNumber(firstIndex);
int thirdIndex = newDifferentRandomNumber(firstIndex, secondIndex);
img1.setImageResource(images[firstIndex]);
img2.setImageResource(images[secondIndex]);
img3.setImageResource(images[thirdIndex]);
}
});
/**
* Generates a new random number that is different from the given one.
*/
private int newDifferentRandomNumber(int number) {
// generate a random int between 0 and 9
int newDifferentRandomNumber = randomGenerator.nextInt(10);
// check if it is equal to the given number, if yes repeat recursively
if (newDifferentRandomNumber == number) {
newDifferentRandomNumber = newDifferentRandomNumber(number);
}
return newDifferentRandomNumber;
}
/**
* Generates a new random number that is different from the 2 given ones.
*/
private int newDifferentRandomNumber(int oneNumber, int anotherNumber) {
// generate a random int between 0 and 9
int newDifferentRandomNumber = randomGenerator.nextInt(10);
// check if it is equal to one of the given numbers,
// if yes repeat recursively
if (newDifferentRandomNumber == number
|| newDifferentRandomNumber == anotherNumber) {
newDifferentRandomNumber = newDifferentRandomNumber(number);
}
return newDifferentRandomNumber;
}