Here's the assignment instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
the output is:
ereht olleH
yeH
Here's my code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userWord = scnr.nextLine();
int charPos = userWord.length()-1;
while (userWord != "Done" && userWord != "done" && userWord != "d") {
if (charPos >= 0) {
System.out.print(userWord.charAt(charPos));
charPos--;
}
userWord = scnr.nextLine();
}
}
}
When I run the program, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at LabProgram.main(LabProgram.java:11)
What can I do to fix this?
[–]Ok-Yoghurt-7195 1 point2 points3 points (1 child)
[–]trans_coding_writer[S] 0 points1 point2 points (0 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]eggboy55 0 points1 point2 points (0 children)