0

How do I fix this error and what does it mean?

java.lang.ArrayIndexOutOfBoundsException: 5
    at Sort.sort(Sort.java:29)
    at Sort.<init>(Sort.java:13)
    at SortedArray.<init>(SortedArray.java:23)

Here is the code:

import java.util.Scanner;
import java.util.Random;

public class SortedArray
{
    Scanner input = new Scanner(System.in);
    int [] Array;
    Sort sortedArray;
    int sizeOfArray;

    public SortedArray()
    {
        System.out.print("Enter the number of values to put in the array: ");
        sizeOfArray = input.nextInt();
        Array = new int [sizeOfArray];
        System.out.println("");
        for(int i = 0; i < sizeOfArray; i++)
        {
            Random r = new Random();
            Array[i] = r.nextInt(100) + 1;
            System.out.println(Array[i]);
        }
        sortedArray = new Sort(Array, sizeOfArray);
        sortedArray.display();
    } 
}


public class Sort
{
  int[] array;
  int sizeOfArray;
  public Sort(int[] oldArray, int sizeOfOldArray)
  {
    sizeOfArray = sizeOfOldArray;
    array = new int [sizeOfArray];
    for( int i = 0; i < sizeOfArray; i++)
    {
        array[i] = oldArray[i];
    }
    sort();
  }

  public void display()
    { 
       for ( int i = 0; i < sizeOfArray; i++){
           System.out.println(array[i]);
       }
    }

  private void sort()
    {
        for (int i = 0; i < sizeOfArray; i++)
        {
            for (int j = 0; j < sizeOfArray; i++)
            {
                if (array[j] < array[i])
                {
                    swap(i,j);
                }
            }
        }
    }

    private void swap(int x, int y)
    {
        int temp;
        temp = array[x];
        array[x] = array[y];
        array[y] = temp;
  }
}

I get the error when I run the program and enter the value. The program is supposed to sort the numbers from greatest to least. I'm not sure what is wrong.

4

3 回答 3

3

首先,这意味着什么:您有一个数组并试图访问超出其范围的索引(小于 0 或大于或等于数组的长度)。

可能的原因是:

for (int j = 0; j < sizeOfArray; i++)

请注意,您检查的j不是太大,而是在增加i

于 2013-06-14T13:06:02.780 回答
1

问题是内部循环也会增加i,这在这种情况下是不正确的!

private void sort()
{
    for (int i = 0; i < sizeOfArray; i++)
    {
        for (int j = 0; j < sizeOfArray; j++)
        {
            if (array[j] < array[i])
            {
                swap(i,j);
            }
        }
    }
}
于 2013-06-14T13:07:48.567 回答
1

你的问题在这条线上

for (int j = 0; j < sizeOfArray; i++)

它应该是

for (int j = 0; j < sizeOfArray; j++)
于 2013-06-14T13:07:48.750 回答