如何解决Java数组反转任务编译错误-IndexOutOfLimsException:2?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (54)

我正试图扭转数组; 我输入的数组长度超过了所有值。在那之后,我试图逆转它,就像那样:a [i] = a [al - i]在“for construction”中 - for(int i = o; i <al; i ++); 我在那里做错了什么?完整代码:

package com.company;
        import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner s1 = new Scanner(System.in);
        int al = s1.nextInt();
        int a[] = new int[al];
        for (int i = 0; i < al; i++) {
            a[i] = s1.nextInt();
        }
        for(int i = 0; i < al; i++) {
            a[i] = a[al - i];
        }
        for(int i = 0; i < al; i++) {
            System.out.println(a[i]);
        }
    }
}
提问于
用户回答回答于

问题描述:

    for(int i = 0; i < al; i++) {
        //let al=5, so index of a will be 0..4
        //so for first iteration i=0
        //so a[5-0] i.e: a[5] where 5 is index out of bound
        a[i] = a[al - i];
    }

解决问题,但这个逻辑不会反转您的数组数据:

for(int i = 0,j=al-1; i < al; i++,j--) {
            a[i] = a[j];
}

要反转数组数据,必须像这样使用:

 for (int i = 0, j = al - 1; i < j; i++, j--) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }

那么,整体解决方案,

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner s1 = new Scanner(System.in);
        int al = s1.nextInt();
        int a[] = new int[al];
        for (int i = 0; i < al; i++) {
            a[i] = s1.nextInt();
        }

        for (int i = 0, j = al - 1; i < j; i++, j--) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        for (int i = 0; i < al; i++) {
            System.out.println(a[i]);
        }
    }
}

扫码关注云+社区

领取腾讯云代金券