IndexOutOfBound从最后打印数组

时间:2015-01-29 10:50:57

标签: java indexoutofboundsexception

我正在尝试从最后一个元素到第一个元素读取一个数组,并在某些情况下更改它们。但是,我不知道为什么我会得到索引超出范围的例外。

public class Test
{
    private Scanner scan = new Scanner ( System.in );

    private int dimension;

    private int[] a;

    public int getDimension() {
        return dimension;
    }

    public void setDimension(int dimension) {
        this.dimension = dimension;
    }

    public Test(int dimension) {
        System.out.println("Add elements");
        setDimension(dimension);
        this.a = new int[this.dimension];
        for(int i = 0; i < this.dimension; i++)
            a[i] = scan.nextInt();
    }

    public void calc() {
        int aux = 0;
        for(int i = a.length-1; i >= 0; i--)
            if(a[i] > a[i-1]) {
                aux = a[i-1];
                a[i-1] = a[i];
                a[i] = aux;
            }
        for(int i = 0; i < getDimension(); i++)
            System.out.print(a[i] + " ");
    }

    public static void main(String[] args) {
        Test p = new Test(5);
        p.calc();
    }
}

1 个答案:

答案 0 :(得分:5)

for(int i = a.length-1; i >= 0; i--)
    if(a[i]>a[i-1]){

i=0时,您指向a[-1]

将其更改为for(int i = a.length-1; i > 0; i--),除非有其他问题,否则它应该有效