java实现定义一个长度为8的数组,里面的元素值随便给,从控制台输入两个数字作为下标,交换对应下标位置的元素值, 例如 输出数字为2和3,交换下标2和下标3位置的元素值
时间: 2024-04-30 20:24:18 浏览: 148
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
Scanner scanner = new Scanner(System.in);
System.out.print("请输入下标1:");
int index1 = scanner.nextInt();
System.out.print("请输入下标2:");
int index2 = scanner.nextInt();
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
阅读全文