Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 交换数组中的相应元素_Java_Arrays - Fatal编程技术网

Java 交换数组中的相应元素

Java 交换数组中的相应元素,java,arrays,Java,Arrays,如何使用循环切换数组中的对应元素,例如:First和last,Second和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++; }

如何使用循环切换数组中的对应元素,例如:First和last,Second和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++;
}

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

您应该只在数组中循环一半,即当k您正在迭代整个数组,这意味着您将撤销在迭代的前半部分中所做的操作。只需迭代数组长度的一半。这应该起作用:

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < (a.length / 2)) {
temp = a[k];
a[k] = a[a.length - 1 - k];
a[a.length - 1 - k] = temp;
k++;
}
easier way 
for(int i=0,j=a.length-1;i<j;i++,j--)
{
  int temp=a[i];
  a[i]=a[j];
  a[j]=temp;
}