I am trying to reverse a string WITHOUT using StringBuilder. I have written the below code but it is giving an error as soon as it hits the loop. The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 16
at lectures.ReverseString.main(ReverseString.java:38)
if anyone could tell me why that would be great. FYI I realize this code is not efficient or elegant but I want to know why it isn't working for education.
public static void main(String[] args) {
//declare variables
Scanner input = new Scanner(System.in);
String myString = "";
int length = 0, index = 0, index2 = 0;
//get input string
System.out.print("Enter the string you want to reverse: ");
myString = input.nextLine();
//find length of string
length = myString.length();
index2 = length;
//convert to array
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
//loop through and reverse order
while (index<length) {
stringChars2[index] = stringChars[index2];
index++;
index2--;
}
//convert back to string
String newString = new String(stringChars2);
//output result
System.out.println(newString);
//close resources
input.close();
}
index2 = length - 1;remember arrays are indexed from 0 ... length - 1