I'm trying to reverse a string in Java but I get an error I don't understand when I run it:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at ReversingText.reverse(ReversingText.java:13)
at ReversingText.main(ReversingText.java:27)"
This is my code:
import java.util.Scanner;
public class ReversingText {
public static String reverse(String text) {
int i = (text.length() - 1);
String letter = "";
while (i >= 0) {
char character = letter.charAt(i);
letter += character;
i--;
}
return letter;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type in your text: ");
String text = reader.nextLine();
System.out.println("In reverse order: " + reverse(text));
}
}
Not sure where the problem is, as I think index starts at 0 so I decrease length of the string by 1 to find index?
Thanks for any help