希望标题能解释我想要的。我想要一组随机顺序的数字 1-12,但没有得到空结果。
这是我的代码:
Integer[] arr = new Integer[12];
for(int i = 1; i < arr.length; i++)
{
arr[i] = i+1; //With this not being i+1, I get 0-11. Like this, I get null-12 and no 1.
if (arr[i] == null)
{
arr[i] = 1;
}
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.asList(arr));
这是我得到的输出:
[null, 5, 3, 10, 7, 2, 9, 4, 6, 12, 8, 11]
我如何转换 null,因为我的 if 语句什么都不做?
最佳答案
您没有初始化数组中的第一个元素。在你的循环中从 i = 0 开始,像这样:
for(int i = 0; i < arr.length; i++)
关于java - 生成不为空的随机数1-12?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756089/