Your approach of comparing each number with all the other numbers is correct in principle.
If we compare the ith element of the array with all the other elements, and none are equal to it, then we know it is the unique number.
Your program is not doing this correctly.
Think of the loops like this:
- The outer loop using the index
i
is giving us the number we are checking for loneliness, a.get(i)
.
- The inner loop using the index
j
is giving us each number to check against the current candidate selected by the outer loop, a.get(j)
.
So for each iteration of the outer loop we will need to keep track of whether any iteration of the inner loop matched. We could use a local boolean
named equalNumberFound
, which we set to false
at the start of each iteration of the outer loop.
In the inner loop, we check whether we've found an equal number, and if we have, set it to true
. Make sure that you don't check a number against itself!
At the end of each iteration of the outer loop, we check equalNumberFound
, and if it's still false
we can return the current outer loop number, because we now know that no other number was equal.
You need to review what you know about while
loops, as it seems you have some incorrect assumptions about how they behave.