能正常编译,输入6个整数后就提示数组索引越界异常- import java.util.Scanner;
- class Array3 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int[] arr = new int[6];
- for (int i = 0;i < 6 ;i ++ ){
- System.out.println("请输入6个整数:");
- arr[i] = sc.nextInt();
- }
- reverseArray(arr);
- change1(arr);
- change2(arr);
- print(arr);
- }
-
- public static void reverseArray(int[] arr) {
- for (int i = 0;i < arr.length/2 ;i ++ ){
- int temp = 0;
- temp = arr[i];
- arr[i] = arr[arr.length - i - 1];
- arr[arr.length - i - 1] = temp;
- }
- }
- //将翻转后的数组角标为奇数的互相交换 1和3换, 3和5换,以此类推
- //也就是arr[]
- public static void change1(int[] arr) {
- for (int i = 0;i < arr.length ;i++ ){
- if (i % 2 == 1 && i < arr.length){
- int temp = 0;
- temp = arr[i];
- arr[i] = arr[i + 2];
- arr[i + 2] = temp;
- }
- }
-
- }
- //最后将数组最后一个角标为奇数的元素 和数组中第一个角标为奇数的元素交换
- public static void change2(int[] arr) {
- int temp = 0;
- if (arr.length % 2 == 0){
- temp = arr[1];
- arr[1] = arr[arr.length - 1];
- arr[arr.length - 1] = temp;
- }else{
- temp = arr[1];
- arr[1] = arr[arr.length - 2];
- arr[arr.length - 2] = temp;
- }
- }
- public static void print(int[] arr) {
- for (int i = 0; i < arr.length ;i++ ){
- System.out.print(arr[i] + " ");
- }
- }
- }
复制代码 |
|