How do you compare your own elements with each other in a Java array?

Asked 1 years ago, Updated 1 years ago, 43 views

int arr[] = new int[6];

for (int k = 0; k < 5; k++)

             {
                arr[k] = (int)(Math.random()*100);

            }

for(int s = 0;s<5;s++)

            {

             while(arr[s] == 0)
                    {
                     arr[s] = (int)(Math.random()*100);
                     }


                        while(arr[s] == arr[s+1]) 
                                {
                            arr[s+1] = (int)(Math.random()*100);

                            System.out.print ("replaced");
                                }




            }

Create an array of arr I'll put in a random number You want to make each element different. So, we compare S and S+1 and if it's the same, we'll make a code until we get another number comes out It's an arrangement with the same number What should I do?

java array element

2022-09-22 13:43

1 Answers

while(arr[s] == 0)
{
  arr[s] = (int)(Math.random()*100);
}

I'm not sure about this part, so let's move on.

The reason why we get the same number is because

Currently, only adjacent indexes are compared.

To maintain the above logic, if you take a random number, you have to compare all the elements in the array each time.


2022-09-22 13:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.