排序整数数组时出现java.lang.ArrayIndexOutOfBoundsException

时间:2015-09-13 05:07:37

标签: java arrays sorting

情景:

我需要从标准输入流中读取一个整数数组,对其进行重新排序,使得素数始终跟随两个偶数,确保从数组中按顺序拾取素数和偶数。它们存在于构建prime-2even集合。任何不能成为该集的一部分的剩余数字都可以 按照它们出现的顺序放置在数组的末尾。输入(多行)和预期输出(多行)如下:

输入:

8 5 9 7 8 5 4 6 8

预期输出:

5 8 4 7 6 8 9 5

尝试:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int totalElements = Integer.parseInt(scanner.nextLine());

    Integer[] integers = new Integer[totalElements];
    Integer[] primeTwoEvens = new Integer[totalElements];
    Integer[] leftOvers = new Integer[totalElements];

    for (int i = 0; i < integers.length; i++) {
        integers[i] = scanner.nextInt();
    }

    // LOGIC
    int notNullCounter = 0; // Variable to track how many elements of integers array has been set to null.
    while (notNullCounter != integers.length) { // Repeat this process until all the elements of the integers array are null.
        for (int i = 0; i < integers.length; i++) { // Iterate the integers array and check for primeTwoEvens and populate the primeTwoEvens array.
            if (integers[i] != null) { // Is the element of integers array to be processed null? If no, proceed.
                if (isPrime(integers[i])) { // Is the element of integers array prime? If yes, proceed.
                    System.out.println(integers[i] + " is prime..."); // Print statement for debugging purpose.
                    primeTwoEvens[i] = integers[i]; // Since the element of integers array is prime, add it to the primeTwoEvens array.
                    integers[i] = null; // Set this index of integers array to null.
                    notNullCounter++;   // As one element of integers array has been set to null, increment the null counter.


                    int evenCounter = 0; // Variable to track even number occurrences.
                    while (evenCounter != 2) { // Repeat this process until 2 even numbers are not found.
                        for (int j = ++i; j <= integers.length; j++) { // Iterate the remaining elements of integers array and check for next two even numbers.
                            if (isEven(integers[j])) { // Is the element of integers array even? If yes, proceed.
                                System.out.println(integers[j] + " is even..."); // Print statement for debugging purpose.
                                evenCounter++; // Since the element of integers array is even, increment the even counter.
                                primeTwoEvens[++i] = integers[j]; // Since the element of integers array is even, add it to the primeTwoEvens array as well.
                                integers[j] = null; // Set this index of integers array to null.
                                notNullCounter++; // As one element of integers array has been set to null, increment the null counter.
                            }
                        }
                    }
                } /*else { // Element is not prime.

                }*/
            }
        }
        //break;
    }// End of while

    /*System.out.println("@@@@@@@@@@@@ PRINTING THE FINAL SORTED ARRAY  @@@@@@@@@@@@");
    for (Integer integer : integers) {
    System.out.println(integer);
    }*/
}

给我一​​个java.lang.ArrayIndexOutOfBoundsException

输出:

5 is prime...
8 is even...
4 is even...
6 is even...
8 is even...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at Ideone.main(Ideone.java:125)

第125行:

if (isEven(integers[j]))

注意:我只能使用Java标准API和JDK 7。

如何解决问题和最终任务?

2 个答案:

答案 0 :(得分:2)

我认为前一行(在行125之前)应为

for (int j = ++i; j < integers.length; j++)

不是<=

答案 1 :(得分:1)

你可以试试这个:

public static void main(String[] args) {
    // Read your file (I just copy your example to an array)
    Integer[] integers = new Integer[] { 8, 5, 9, 7, 8, 5, 4, 6, 8 };

    List<Integer> prime = new ArrayList<Integer>(), even = new ArrayList<Integer>();
    List<Integer> other = new ArrayList<Integer>(), ordered = new ArrayList<Integer>();

    // Start adding until 1st prime appear
    boolean firstPrime = false;

    for (Integer number : integers) {
        if (isPrime(number)) {
            prime.add(number);
            firstPrime = true;
        } else if (firstPrime && isEven(number)) {
            even.add(number);
        }

        // To have control of the order of appearance
        if (firstPrime) other.add(number);

        // If I have at least 1 prime and 2 even, then add them
        // to my ordered list and remove them from all my other lists
        if(prime.size() >= 1 && even.size() >= 2){
            ordered.add(prime.get(0));
            ordered.add(even.get(0));
            ordered.add(even.get(1));

            other.remove(prime.get(0));
            other.remove(even.get(0));
            other.remove(even.get(1));

            even.remove(1);
            even.remove(0);
            prime.remove(0);
        }
    }

    ordered.addAll(other);

    System.out.println(ordered);
}

如果你运行这个例子,你将有

[5, 8, 4, 7, 6, 8, 9, 5]