The error comes after the user inputs 5 separate numbers. I am not sure why I am getting this error. There are no errors shown in Eclipse and I am able to run the code.
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at section8.arraysLists.Main.main(Main.java:33)"
Here is my code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 5;
System.out.println("Enter " + number + " numbers to sort:");
int[] array = new int [number];
for (int i=0; i<array.length; i++) {
array[i] = scanner.nextInt();
}
int[] sortedArray = Arrays.copyOf(array, array.length);
boolean flag = true;
int temp;
while (flag) {
flag = false;
for (int i=0; i<sortedArray.length; i++) {
if (sortedArray[i] < sortedArray[i]+1) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i]+1;
sortedArray[i+1] = temp;
flag = true;
}
}
}
System.out.println("--Sorted Array--");
System.out.println("Element 0 is " + sortedArray[0]);
System.out.println("Element 1 is " + sortedArray[1]);
System.out.println("Element 2 is " + sortedArray[2]);
System.out.println("Element 3 is " + sortedArray[3]);
System.out.println("Element 4 is " + sortedArray[4]);
System.out.println("Element 5 is " + sortedArray[5]);
}
}
Output
Enter 5 numbers to sort:
1
5
6
7
87
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at section8.arraysLists.Main.main(Main.java:33)