0

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)
jayweezy
  • 81
  • 8
  • The very last line is wrong: `System.out.println("Element 5 is " + sortedArray[5]);` . Arrays are zero-indexed, so `sortedArray[5]` is the *sixth* element in an array that only has five elements. I'd suggest using a loop to print out the contents of the sorted array. – Jordan Feb 04 '20 at 20:31
  • I deleted the last line and now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at section8.arraysLists.Main.main(Main.java:31)" – jayweezy Feb 04 '20 at 20:34
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – RaminS Feb 04 '20 at 20:35
  • `sortedArray[i+1] = temp;`You are referring `4+1`th element in last iteration – JMD Feb 04 '20 at 20:36

2 Answers2

1

You are trying to print six elements, but your array has only five elements: index of array are zero-based, then an array of five elements has only the following indexes valorized: 0, 1, 2, 3, 4.

EDIT

There are three errors with your insertion sort:

 for (int i=0; i<sortedArray.length; i++) {
      if (sortedArray[i] < sortedArray[i]+1) { // here you have 
                        // to compare two consecutives array's values... 
                       // in this manner this condition is always true!
            temp = sortedArray[i];
            sortedArray[i] = sortedArray[i]+1; // like previous one
            sortedArray[i+1] = temp; // here --> ArrayOutOfBound when i = 4

            flag = true;
          }
      }

Maybe the correct code should be:

 for (int i=0; i<sortedArray.length - 1; i++) {
      if (sortedArray[i] < sortedArray[i+1]) {
            temp = sortedArray[i];
            sortedArray[i] = sortedArray[i+1];
            sortedArray[i+1] = temp;

            flag = true;
          }
      }
Renato
  • 2,077
  • 1
  • 11
  • 22
  • Okay. I deleted the last line though and now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at section8.arraysLists.Main.main(Main.java:31)" – jayweezy Feb 04 '20 at 20:35
  • Edited the answer – Renato Feb 04 '20 at 20:41
  • Works now! Thanks! – jayweezy Feb 04 '20 at 20:48
  • I am glad you found the solution useful. In these cases you can accept the solution by clicking on the check mark beside the answer to toggle it from greyed out to filled in. Thank you! – Renato Feb 04 '20 at 20:55
0

Look at this loop:

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

Now the loop is going have values for i ranging from 0 to 4. This is fine. However, in the line pointed out, you will attempt to index sortedArray[i+1]. When i==4, this becomes sortedArray[5] which is out of bounds for the same reason you had to delete the last line.

Also, you are looking a lot at sortedArray[i]+1, which is adding 1 to the value of the array. This is likely not correct. I suspect what you want to do is the following:

        for (int i=1; i<sortedArray.length; i++) {
            if (sortedArray[i-1] < sortedArray[i]) {
                // The smaller value is in front of the bigger.  We need to swap
                temp = sortedArray[i];
                sortedArray[i] = sortedArray[i-1];
                sortedArray[i-1] = temp;

                flag = true;
            }
        }
Trenin
  • 2,041
  • 1
  • 14
  • 20
  • Thanks! This works too but I prefer the other answer because I only needed to change 1 thing which was adding a "-1" to the end of "sortedArray.length" – jayweezy Feb 04 '20 at 20:52