【问题标题】:ArrayIndexOutOfBoundExceptions on certain inputs when sorting elements of an array?对数组元素进行排序时,某些输入上的 ArrayIndexOutOfBoundExceptions?
【发布时间】:2015-09-15 06:46:14
【问题描述】:

我的任务是编写一个函数来重新排列数组,以便奇数出现在数组的开头,从大到小,偶数从小到大出现在最后。我们不允许使用除标准输入和输出流之外的任何其他库。

当数字为时输出有效:

{-15, 450, 6, -9, 54}

但如果我将元素更改为:

{-55, 45, 6, 11, 54}

出现异常错误。这是我的代码:

public class ary1 {
    public static void sort(int A[], int n) {
        int tmp;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (A[0] % 2 == 0) //even
                {
                    if (A[i] < A[j]) {
                        tmp = A[i];
                        A[i] = A[j];
                        A[j] = tmp;
                    }
                } else {
                    if (A[i] > A[j]) {
                        tmp = A[i];
                        A[i] = A[j];
                        A[j] = tmp;
                    }
                }
            }
        }
    }

    public static void showAray(int A[], int n) {
        for (int i = 0; i < n; i++) {
            System.out.println(A[i]);
        }
    }

    public static void main(String args[]) {
        int array1[] = {-55, 45, 6, 11, 54};
        int odd = 0;
        int even = 0;

        for (int i = 0; i < array1.length; i++) {
            if (array1[i] % 2 == 0) {
                even++;
            } else {
                odd++;
            }
        }

        int[] array2 = new int[even];
        int[] array3 = new int[odd];

        for (int i = 0, j = 0, k = 0; i < array1.length; i++) {
            if (array1[i] % 2 == 0) {
                array2[j++] = array1[i];
            } else {
                array3[k++] = array1[i];
            }
        }

        System.out.println("Original array:\n");
        showAray(array1, array1.length);

        sort(array2, even);
        sort(array3, odd);

        for (int i = 1; i < array1.length; i++) {
            if (i < odd) {
                array1[i] = array3[i];
            } else {
                array1[i] = array2[(i + 1) - even];
            }
        }

        System.out.println("\nAfter sorting:\n");
        showAray(array1, array1.length);
    }
}

我知道这里有一个逻辑错误,但我无法弄清楚究竟是什么。有没有办法改变逻辑以处理所有整数?谢谢。

array1[i] = array2[(i + 1) - even];

编辑 - 这是堆栈跟踪。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ary.main(arytest.java:67)
Java Result: 1

【问题讨论】:

  • "出现异常错误。" - 请与我们分享堆栈跟踪,并在代码中指出发生异常的行。

标签: java arrays exception


【解决方案1】:

改变这个

array1[i] = array2[(i + 1) - even];

array1[i] = array2[i - odd];

我想这就是你想要的

【讨论】:

  • 没错。但最好解释一下原因;)
  • 不,1+1 很容易解释。不要想太多!
  • 请给我解释一下:)
  • 如果不是评论,我会的。拍两张苹果的照片就可以了:一加一,你就得到了两个苹果:)))
  • 谢谢,但这不是我们在数学中的做法。
猜你喜欢
  • 2013-03-25
  • 1970-01-01
  • 2020-05-18
  • 2021-02-16
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多