1

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

roshanpeter
  • 1,334
  • 3
  • 13
  • 32
  • [This question](https://stackoverflow.com/questions/10242380/how-can-i-generate-a-list-or-array-of-sequential-integers-in-java) has couple of suggestions. – Taha Dec 01 '21 at 18:56
  • 1
    Why don't u start your for-loop with `int i = 1`? – csalmhof Dec 01 '21 at 18:56

2 Answers2

1

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 and in addition you also need to change the condition of the for loop to arr.length + 1 or i <= arr.length, so it will count up to 7.

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

What you also can do instead of changing the loop itself, is to change the loop body. Just add 1 to i when assigning it to arr[i]:

for (int i = 0; i < arr.length; i++) {
    arr[i] = i + 1;
}

In this case i will count from 0 to 6, and assign 1 to 7 to your array

csalmhof
  • 1,820
  • 2
  • 15
  • 24
  • 1
    But when I am changing i to 1 I am getting array with 1-6 and one elemnt is null value – roshanpeter Dec 01 '21 at 19:12
  • sry. i missed that point at first sight. Adapted my answer to meet your criteria. Of course you also need to change the condtion to `i < arr.length + 1` or `i <= arr.length` in this case – csalmhof Dec 01 '21 at 19:18
  • 1
    I also added a imho easier solution at the bottom of my answer. You also can just change the assignment-statement in the loop body. – csalmhof Dec 01 '21 at 19:39
  • Yes thats is working – roshanpeter Dec 01 '21 at 19:42
0

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

   Integer[] arr = new Integer[7];
        for(int i = 1; i <8; i++){
            int value = i-1;
            arr[value] = i;
        }

        Collections.shuffle(Arrays.asList(arr));
        for(int i = 0; i < arr.length; i++){
                System.out.println("Result:"+arr[i]);
        }

Console message:

Result:7
Result:2
Result:6
Result:5
Result:4
Result:1
Result:3
Ole Pannier
  • 3,208
  • 9
  • 22
  • 33