gpt4 book ai didi

java - 如何从随机数系列中排除某个数字?

转载 作者:行者123 更新时间:2023-12-01 18:28:14 24 4
gpt4 key购买 nike

我正在开发一个骰子游戏。我正在生成一个随机数字,介于 1 到 6 之间。我的骰子显示相同的数字。所以它工作得很好。但是在一个条件之后,我希望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;
}
};

最佳答案

您首先使用允许的值填充列表,然后在此列表的范围内生成随机索引。

List<Integer> allowedValues = Arrays.asList(1,3,4,5,6);
Random rd = new Random();
int selected = allowedValues(rd.nextInt(allowedValues.size()));

关于java - 如何从随机数系列中排除某个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com