I am looking for a way to reverse the word in java. This is my code and it occurs errors.
Can somebody explain why?
import java.util.Scanner;
public class Robot {
public static void reverse(String text) {
int leng = text.length();
int i = 0;
while (leng-i>=0){System.out.print(text.charAt(leng-i));
i++;
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type in your text: ");
String text = reader.nextLine();
System.out.print("In reverse order: ");
reverse(text);
}
}
I expected it to reverse the order of the word but it does not.
It should be
int i = 1;
Otherwise, you will be getting a StringIndexOutOfBoundsException
since text.length()
is never a valid index.
To make it a bit shorter (and cooler), you might want to write
System.out.print(text.charAt(leng - i++));
Though, we usually do
System.out.print(new StringBuilder(text).reverse());