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;
}
}
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...
It should be: numbers = eliminateDuplicates(numbers);
You were essentially ignoring the returned result from the method.
Do like this:
int[] result =eliminateDuplicates(numbers);
for (int y = 0; y < result.length; ++y)
System.out.print(numbers[y] + " ");
Also, In your eliminateDuplicates()
method, use result
array directly by removing temp
array. Or rename temp
to result
and return it. Following code is unnecessary :
int[] result = new int[size];
for (int z = 0; z < result.length; ++z)
result[z] = temp[z];
在你的主要,试试这个:
numbers = eliminateDuplicates(numbers);
Method calling should be like this -
numbers = eliminateDuplicates(numbers);
You are not catching the result returning by eliminateDuplicates function.
In Java, parameters are passed by value , so you can't use numbers
as an in/out parameter.
eg if you C# you could have done
eliminateDuplicates(ref numbers);
But as others have pointed out, the most obvious issue is that you forgot to assign the result :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.