简体   繁体   中英

java.lang.ArrayIndexOutOfBoundsException Error

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.

First, what it means: you have an array and are trying to acces an index that is outside its range (below 0 or bigger or equal than the length of the array).

The probable cause is:

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

Notice that you check that j does not get too big but you are increasing i .

The Problem is that the inner loop also increments i which isn't correct in this situation!

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);
            }
        }
    }
}

Your problem is on this line

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

it should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM