2

I am trying to print every number that has an index above the median. However, i keep getting this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Test.main(Test.java:10)

Here is my code:

public class Test {
public static void main(String[] args) {
int list[] = {1,2,3,4,5};
int list1[] = new int[2];
int start = (int)(Math.ceil(list.length/2));
String output = "";

 for(int i = start; i < list.length; i++) {
    int indexB = (i - 3);
    list1[indexB] = list[i]; //The error is concerned about this line of code        
 }
    for(int j = 0; j < list1.length; j++) {
       output += list1[j] + " ";
    }
       System.out.print(output); 


  }
}

1 Answers1

0

Problem is here,

int start = (int)(Math.ceil(list.length/2)); return 2 whereas

`int start = (int) (Math.ceil((double) 5 / (double) 2));` returns 3
int indexB = (i - 3);

Here i = start = 2, so indexB becomes -1, which is not an index

so it throws java.lang.ArrayIndexOutOfBoundsException: -1

Also loop starts from i=2 -> i<5, so for values of i=2,3,4

Some code changes

public static void main(String[] args) {
        int list[] = { 1, 2, 3, 4, 5 };
        int start = (int) (Math.ceil(list.length / 2));

        int list1[] = new int[list.length  - start];
        String output = "";

        for (int i = start; i < list.length; i++) {
            int indexB = (i - start);
            list1[indexB] = list[i]; // The error is concerned about this line
                                        // of code
        }
        for (int j = 0; j < list1.length; j++) {
            output += list1[j] + " ";
        }
        System.out.print(output);

    }

output

3 4 5 
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116