简体   繁体   中英

Removing a number from array in Java

I would like to remove a particular number from the array

Integer[] arr = new Integer[7];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
        Collections.shuffle(Arrays.asList(arr));

This is creating numbers from 0-7 But I dont need 0,I need value from 1-7

Change your int i = 0 to int i = 1 like this:

Integer[] arr = new Integer[7];
        for (int i = 1; i < arr.length; i++) {
            arr[i] = i;
        }
        Collections.shuffle(Arrays.asList(arr));

The first value written into your array is 0 because you initialize i with 0 in the for loop.

Therefore your loop will only insert the values 0 - 6 .

Change this initialisation to i = 1 .

Integer[] arr = new Integer[7];
for (int i = 1; i < arr.length; i++) {
    arr[i] = 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM