-1

I've got a problem with my Code. Whatever I do , I receive an IndexOutOfBoundException at the line with the if-statement. I've already tried everything. The programm should usually check the values of the indices always at the first and at the last position of an integer-Array. If the values are equal it's gonna be outprinted, if they aren't equal,too. Thanks for your help!

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[]test = new int[] {3,4,5,5,4,3};
    IntSym(test);
    System.out.println(test.length);

}

public static void IntSym(int[]test) {
    for(int j=0; j<=test.length/2;j++) {
        if(test[j]==test[test.length-j]) {
            System.out.println(j+"."+ (test.length-j) +". are equal");
        }else{
            System.out.println(j+"."+ (test.length-j) +". aren't equal");
        }
    }
}
developox
  • 3
  • 4

1 Answers1

3

In the first iteration since j=0 then test[test.length-j] will throw the ArrayIndexOutOfBoundsException.

To solve the problem replace it with test[test.length-j-1]:

public static void IntSym(int[]test) {
    for(int j=0; j<=test.length/2;j++) {
        if(test[j]==test[test.length-j-1]) {
            System.out.println(j+"."+ (test.length-j) +". are equal");
        }else{
            System.out.println(j+"."+ (test.length-j) +". aren't equal");
        }
    }
}
STaefi
  • 4,297
  • 1
  • 25
  • 43