【发布时间】:2020-04-28 20:11:07
【问题描述】:
我需要以随机顺序获取数字 0-11,并确保每个数字只获取一次。不过,它仍在向我的 Line2 班级发送相同的号码。如何确保 int 变量 lineChoice 每次都完全不同? 我的问题是 if/else 没有正确确保我没有将已选择的 lineChoice 发送到我的 Line2 类。
for(int i = 0; i < 12; i++){
//get a random line choice 0-11
lineChoice = (int)(Math.random() * 11); //0-11;
//if that number was already chosen
//get a new random number and add it to the array
if(randomNumbers.contains(lineChoice)){
lineChoice = (int)(Math.random() * 11); //0-11;
randomNumbers.add(lineChoice);
}else{
//if not already in array, add to array
randomNumbers.add(lineChoice);
}
//make a Line based on the random lineChoice number
line = new Line2(lineChoice);
//add the line to the string poem
poem += "\n" + line + "\n\n\n";
}
【问题讨论】:
标签: java arrays arraylist random