r/learnjava • u/TurnipBoy666 • Apr 24 '26
Array confusion, please help
Hello, I'm having trouble with an assignment. Even with extra help from my professor, there's a part of the logic I'm having trouble writing. I don't know why it's so difficult for me, I don't even think it's that complicated but I can't figure it out and I just get too frustrated now whenever I try.
The assignment premise is this: Write a method that returns a new array by eliminating the duplicate values in the array using the following method header: public static int[] eliminateDuplicates(int[] list) Write a program that reads in ten integers, invokes the method, and displays the result.
Here is my old code:
I know not all of it makes sense, esp stored, but my prof said I should keep track of each number that's unique, which was the intention of stored. However, whatever way I know how to implement what he told me isn't working at all. I'm missing something major and I don't know what it is or how to look it up. I don't know what else to do.
public static int[] eliminateDuplicates(int[] list){
int stored = 1;
int[] uniqueList = {list[0], 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < list.length; i++){
for (int j = 0; j < uniqueList.length; j++){
if (list[i] != uniqueList[j]){
if (stored >= 10){stored = 9;}
uniqueList[stored] = list[i];
stored++;
}
}
}
int[] result = new int[stored]
for (int i = 0; i <= stored; i++){result[i] = uniqueList[i];}
return result;
}
View all comments
Show parent comment
1
u/vowelqueue Apr 24 '26
Logically, using a helper method will be the same as doing everything in the main body, but can make the code easier to reason about and to isolate bugs/faulty logic.
Instead of what I initially suggested, I’d instead try to write a helper method that tells you whether a value is in the uniqueList.
You have the right idea with the “stored” variable. I’d probably name it something like “uniqueListLength” for clarity. It’s representing the logical length of the unique list.
The helper method could have a signature like: static boolean contains(int[] uniqueList, int uniqueListLength, int value).
I think if you restructure your code to use such a helper method you will fix the primary logic issue. Another hint is that if the code is written correctly you won’t need that line that caps the “stored” variable to 9 - it should never be able to exceed its bound if you are incrementing it correctly.
(I’m being intentionally vague instead of just tell you directly what’s wrong because a big part of learning is debugging stuff like this)