该程序抛出ArrayIndexOutOfBoundException,如何克服?

时间:2016-02-23 04:29:14

标签: java

该程序运行正常但抛出数组索引超出限制异常,请帮助如何克服此问题?该程序工作正常,但抛出数组索引超出限制异常,请帮助如何克服这个问题?

package coreJava;

import java.util.Scanner;

public class Practice {
    public static int count = 0;
    public static int position = 0;
    public static boolean flag = false;

    public static void main(String[] args){
       // int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };

         Scanner s = new Scanner(System.in);
         System.out.print("Enter number of elements you want in array:");
         int n = s.nextInt();
         int a[] = new int[n];
         System.out.println("Enter all the elements:");

         for (int i = 0; i < n; i++) {
             a[i] = s.nextInt();
         }

         findMissingNumbers(a, position);
    }

    private static void findMissingNumbers(int a[], int position) {
        if (position == a.length - 1)
            return;

        for (; position < a[a.length - 1]; position++) {
            if ((a[position] - count) != position) {
                System.out.println("Missing Number: " + (position + count));
                flag = true;
                count++;
                break;
            }
        }

        if (flag) {
            flag = false;
            findMissingNumbers(a, position);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

变化:

for (; position < a[a.length - 1]; position++)

为:

for (; position < a.length; position++)

答案 1 :(得分:0)

在行中,if((a [position] - count)!= position){

你可能会得到例外。这是因为位置可能高于a.length-1请检查算法。因为输入的第一个数字可能比其他输入值小。