我正在开发一个骰子游戏。我正在生成一个随机的no,在1到6之间。我的骰子显示相同的no。所以它工作得很好。但是在一个条件之后,我想要那个,2个一定不能来,所以如何在1到6之间删除2.这是我的代码。
Random rng = new Random();
btnSpin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!rolling) {
dice_picture.setImageResource(R.drawable.dice3d);
timer.schedule(new Roll(), 400);
}
}
});
}
// code of dice...
class Roll extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
}
Callback callback = new Callback() {
public boolean handleMessage(Message msg) {
switch (rng.nextInt(6) + 1) {
case 1:
dice_picture.setImageResource(R.drawable.one);
icon = "one";
Toast.makeText(getApplicationContext(),
"The value is one" + one, Toast.LENGTH_SHORT).show();
break;
case 2:
dice_picture.setImageResource(R.drawable.two);
icon = "two";
Toast.makeText(getApplicationContext(),
"The value is two" + two, Toast.LENGTH_SHORT).show();
break;
case 3:
dice_picture.setImageResource(R.drawable.three);
icon = "three";
Toast.makeText(getApplicationContext(),
"The value is three" + three, Toast.LENGTH_SHORT)
.show();
break;
case 4:
dice_picture.setImageResource(R.drawable.four);
icon = "four";
Toast.makeText(getApplicationContext(),
"The value is four" + four, Toast.LENGTH_SHORT).show();
break;
case 5:
dice_picture.setImageResource(R.drawable.five);
icon = "five";
Toast.makeText(getApplicationContext(),
"The value is five" + five, Toast.LENGTH_SHORT).show();
break;
case 6:
dice_picture.setImageResource(R.drawable.six);
icon = "six";
Toast.makeText(getApplicationContext(),
"The value is six" + six, Toast.LENGTH_SHORT).show();
break;
default:
}
rolling = false; // user can press again
return true;
}
};
答案 0 :(得分:4)
首先使用允许的值填充列表,然后在此列表的边界中生成随机索引。
List<Integer> allowedValues = Arrays.asList(1,3,4,5,6);
Random rd = new Random();
int selected = allowedValues(rd.nextInt(allowedValues.size()));