1.交换两个数的值.
public class ArrayTest6 {
public static void main(String[] args) {
//交换两个变量的值
int a = 10;
int b = 20;
//交换
int temp;
temp = a;
a = b;
b = temp;//这里要是temp
System.out.println(a);
System.out.println(b);
}
}
2.交换数组第一个和最后一个的值.
public class ArrayTest7 {
public static void main(String[] args) {
//交换数组首尾的值
int[] arr = {1,2,3,4,5};
int temp;
temp = arr[0];
arr[0] = arr[arr.length-1];
arr[arr.length-1] = temp;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
3.交换数组开头和结尾的值
public class ArrayTest8 {
public static void main(String[] args) {
//交换数组前后元素值
int[] arr = {1,2,3,4,5};
for (int i = 0,j = arr.length - 1;i < j;i++,j--){
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}