java - 创建不在数组中的随机数
问题描述
我有许多应该随机选择的开关盒,但每个开关盒只能选择一次。我制作了一个随机生成器和一个用于添加案例的数组,但我卡住了,因为我的代码不太好。这是我目前拥有的
public void showRandomButton() {
//Generate Random Numbers
final int min = 0;
final int max = 13; //n-no of random events
Random g=new Random();
int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)
while(Arrays.asList(list).contains( random )) {
int numb = g.nextInt((max - min) + 1) + min;
random = numb;
}
switch(random){
case 1:
mbutton1.setVisibility( View.VISIBLE );
mbuttonStart.setVisibility( View.GONE );
break;
case 2:
mbutton2.setVisibility( View.VISIBLE );
mbuttonStart.setVisibility( View.GONE );
break;
//Function 2 break;
谢谢你的帮助
解决方案
试试这个:
int min = 0;
int max = 13;
List<Integer> list = new ArrayList<Integer>();
for(int i = min; i <max;)
{
int rand = ((int)(Math.random() * max)) + 1;
if(!list.contains(rand))
{
list.add(rand); // it will be added only if not in list
i++;
}
}
推荐阅读
- html - HTML 和 CSS 背景更改
- python - 在 Python 中生成序列递归定义的数学字符串
- grep - 我正在尝试使用 FTK 查找信用卡
- python - Python doc:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None 中的方括号是什么意思?
- r - 如何创建一个将列表中每个非数字元素转换为 as.numeric 的函数?
- java - com.oauth.server.security.CustomUserDetailsService 中构造函数的 Spring Boot 参数 0 需要一个 bean 类型
- java - 带有轮数和计数器变量的 Rockpapergame - java
- c++ - 从 unordered_set 中获取给定大小 k 的所有子集?
- php - 如何使用 localhost 将数据发送到数据库
- cloud - ovh 专用服务器上的 1 gbps 包括带宽的限制?