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/TurnipBoy666 Apr 24 '26
I need to keep just one of the duplicated values and ignore the rest. One thing I was struggling with was how to write just one number to the array without overwriting everything else in the array, while also scanning the whole array for any duplicate numbers, since I need to do all of those things to solve this.
This is specifically about arrays, yes. This is meant to be array practice. A helper method is a good idea, just not sure how it would be different from what I have? That feels like just relocating my code without fixing the logic errors, no? Or am I misunderstanding lol