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

2
  • This question has couple of suggestions. Commented Dec 1, 2021 at 18:56
  • 1
    Why don't u start your for-loop with int i = 1? Commented Dec 1, 2021 at 18:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

But when I am changing i to 1 I am getting array with 1-6 and one elemnt is null value
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
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.
Yes thats is working
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

3 Comments

But when I am changing i to 1 I am getting array with 1-6 and one elemnt is null value
Here you go. Now you have your 1-6 with a shuffle. Cheers!
I am not diplaying the contents..I need the array without value 0. From this array I am doing something else

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.