交换数组中的相应元素

0 java arrays

我如何使用循环切换数组中的相应元素(例如:First with last,Second with one before last).我已经使用循环编写了代码,但它没有在Eclipse中提供所需的结果.

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < a.length)
{
  temp = a[k];
  a[k] = a[a.length - 1 - k];
  a[a.length - 1 - k] = temp;
  k++;
}
Run Code Online (Sandbox Code Playgroud)

假设您不知道数组中的值或它的长度.

cas*_*nca 6

你应该只在数组的中途循环,即while (k < a.length / 2)- 如果你继续超过它,你将最终将交换的元素交换回原始位置.