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.