Hopefully the title explains what I want. I want a set of numbers 1-12 in a random order but not get a null result.
Here is my code:
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));
And here is what I get as an output:
[null, 5, 3, 10, 7, 2, 9, 4, 6, 12, 8, 11]
How can I convert the null because my if statement does nothing?
You're not initializing the first element in you array. Start with i = 0 in you loop, like this:
for(int i = 0; i < arr.length; i++)
从0开始而不是1
for(int i = 0; i < arr.length; i++)
Arrays
are 0 based
, so the first elements should be start from 0
index, not 1
So try to change your code like:
for(int i = 0; i < arr.length; i++)
for more details read more about arrays .
在0
开始for循环
for(int i = 0; i < arr.length; i++)
You are initializing loop variable i to 1 as a result the array arr[0] is never assigned a value which is by default null. Your loop should be for(int i = 0; i < arr.length; i++)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.