I am developing a dice game. I am generating A random no, between 1 to 6. and my dice showing same no. So it is working perfectly. But after a condition, I want that, 2 must not be come, so how can I remove 2 between 1 to 6. Here is my code.
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;
}
};
You first fill a list with the allowed values and then generate a random index in the bounds of this list.
List<Integer> allowedValues = Arrays.asList(1,3,4,5,6);
Random rd = new Random();
int selected = allowedValues(rd.nextInt(allowedValues.size()));