我需要随机获取数字 1-4 并将其存储在 arrayList 中。我有一个好的开始,但我可能有一个无限循环,因为模拟器不断崩溃。这些数字也不能多次使用。
** lightSelector is a global variable (int lightSelector = 1;)
** generatedOrder is my ArrayList
for (int i = 0; i < 4; i++)
{
lightSelector = 1 + (int)(Math.random() * 4);
generatedOrder.add(lightSelector);
boolean contains = true;
System.out.print(generatedOrder.get(i));
if (!generatedOrder.isEmpty())
{
// Loop until a number is generated that hasn't already been picked
while (contains)
{
if (generatedOrder.contains(lightSelector))
lightSelector = 1 + (int)(Math.random() * 4);
else
{
generatedOrder.add(lightSelector);
contains = false;
break;
}
}
}
}