我有一个关于将数组从一个方法返回到 main 的问题。这真的开始让我烦恼,我无法全神贯注于此。似乎即使我在我的方法中更改了数组,当我在 main 中显示它时它也会显示旧数组。我正在尝试删除数组中的重复数字,并且我知道它可以工作,因为我已经在调试器中单步执行了它,但在我返回它并返回到 main 后,它再次显示整个数组!我知道我在这里想念的一定很容易。有人可以指出我正确的方向吗?这是我的代码...
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;
}
}
最佳答案
看看这个调用:
eliminateDuplicates(numbers);
您忽略了返回值。也许你想要:
numbers = eliminateDuplicates(numbers);
有时我希望 Java 有一种方法来指示不应忽略方法的返回值。它还会节省很多关于 InputStream.read
的问题...
关于java - 将数组返回到 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11929031/