ArrayIndexOutOfBoundsException:-1在递归排序中

时间:2013-04-06 18:18:27

标签: java sorting

我是Java的新手,我想知道为什么我有例外,即使我得到了我需要的答案。以下是源代码

package habeeb;

import java.util.*;

public class Habeeb
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int[] num = new int[30];
        int i, count = 0;
        System.out.println("Enter the integers between 1 and 100");
        for (i = 1; i <= num.length; i++)
        {
            num[i] = input.nextInt();
            if (num[i] == 0)
                break;
            count++;
        }
        Sorting(num, i, count);
    }

    public static void Sorting(int[] sort, int a, int con)
    {
        int j, count = 0;
        for (j = 1; j <= con; j++)
        {
            if (sort[a] == sort[j])
                count++;
        }
        System.out.println(sort[a] + " occurs " + count + " times");
        Sorting(sort, a - 1, con);
    }
}

这是输出

run:
Enter the integers between 1 and 100
1
2
3
2
2
4
5
3
6
1
0
0 occurs 0 times
1 occurs 2 times
6 occurs 1 times
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
3 occurs 2 times
5 occurs 1 times
4 occurs 1 times
2 occurs 3 times
2 occurs 3 times
3 occurs 2 times
2 occurs 3 times
1 occurs 2 times
0 occurs 0 times
 at habeeb.Habeeb.Sorting(Habeeb.java:18)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.Sorting(Habeeb.java:21)
 at habeeb.Habeeb.main(Habeeb.java:14)
 Java Result: 1

2 个答案:

答案 0 :(得分:1)

public static void Sorting(int[] sort, int a, int con){
int j, count=0;
for(j=1; j<=con; j++){
  if(sort[a]==sort[j])
   count++;
}System.out.println(sort[a]+" occurs "+count+" times"); 
Sorting(sort, a-1, con);

应该是:

public static void Sorting(int[] sort, int a, int con){
if(a<0)return;
int j, count=0;
for(j=1; j<=con; j++){
  if(sort[a]==sort[j])
   count++;
}System.out.println(sort[a]+" occurs "+count+" times"); 
Sorting(sort, a-1, con);

答案 1 :(得分:1)

问题在于:

for (i = 1; i <= num.length; i++){
    num[i] = input.nextInt();

    if (num[i] == 0)
        break;

    count++;
}
循环中的

i 取值 1 - num.length ,其中 num.length = 30。

所以在某些时候,你的程序试图执行

num[30] = input.nextInt();

会导致错误! Cos 30 超出数组索引的范围。正确的指数范围应介于 0 29 之间。

两种可能的更正是:

从0循环 - (num.length - 1):

for(i = 0; i <= num.length - 1; i++){

    num[i] = input.nextInt();

    if (num[i] == 0)
        break;

    count++;
}

如前所述从1 - num.length循环,但适当更新 num 的索引:

for(i = 1; i <= num.length1; i++){

    int index = i - 1;

    num[index] = input.nextInt();

    if (num[index] == 0)
        break;

    count++;
}