Originally Posted by
NightFire91
Hi,
I have this code which is meant to reverse the array a, however I get a message ArrayIndexOutOfBoundsException - why is this, and how do I correct the code to not get this problem?
you get an ArrayIndexOutOfBoundsException because the index of an array is zero-based and the length field of the array is not zero-based. so if you want to get the last char in the array you must use a[length - 1]. here is the corrected code:
public class MirrorElements {
public static void main(String[] args) {
char[] a = { 'h', 'a', 'l', 'l','o',' ', 'w','o', 'r','l','d'};
StringBuilder sf = new StringBuilder(new String(a));
int i = 0;
while (i < a.length / 2) {
int original = a[i]; // store a[i] before swapping
// swap a[i] with length - i -1
a[i] = a[a.length - i -1];
// store the original char
a[a.length - i -1] = (char)original;
i = i + 1;
}
System.out.println(a);
// the StringBuffer has a reverse() method, so
// use it to check if your a[] is the same
System.out.println(sf.reverse());
}
}
i use a literal of chars for my example but you can change easily to your param. and i used the StringBuilder only for testing purpose. good luck.