Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning arrays to main method

I have a question about returning an array from one method back to main. It is seriously starting to annoy me and I cannot wrap my brain around this. It seems as if even though I have changed the array in my method, when I go to display it in main it displays the old array. I'm trying to remove the duplicate numbers in my array and I know it works because I have stepped through it in the debugger yet after I return it and go back to main, it displays the whole array again! I know it must be something easy that I am missing here. Can someone please point me in the right direction? Here is my code...

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] numbers = new int[10];

    System.out.print("Enter 10 numbers: ");

    for (int x = 0; x < numbers.length; ++x)
        numbers[x] = input.nextInt();

    eliminateDuplicates(numbers);

    for (int y = 0; y < numbers.length; ++y)
        System.out.print(numbers[y] + " ");
}


public static int[] eliminateDuplicates(int[] numbers) {
    int[] temp = new int[numbers.length];
    int size = 0;
    boolean found = false;

    for (int x = 0; x < numbers.length; ++x) {

        for (int y = 0; y < temp.length && !found; ++y) {
            if (numbers[x] == temp[y])
                found = true;
        }
        if (!found) {
            temp[size] = numbers[x];
            size++;
        }
    found = false;
    }   

    int[] result = new int[size];
    for (int z = 0; z < result.length; ++z)
        result[z] = temp[z];

    return result;
}
}
like image 817
Eventh Avatar asked Sep 22 '26 23:09

Eventh


2 Answers

Look at this call:

 eliminateDuplicates(numbers);

You're ignoring the return value. Perhaps you wanted:

 numbers = eliminateDuplicates(numbers);

I sometimes wish that Java had a way of indicating that a method's return value shouldn't be ignored. It would save a lot of questions around InputStream.read as well...

like image 66
Jon Skeet Avatar answered Sep 25 '26 13:09

Jon Skeet


It should be: numbers = eliminateDuplicates(numbers);

You were essentially ignoring the returned result from the method.

like image 32
Petar Minchev Avatar answered Sep 25 '26 11:09

Petar Minchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!