I' m kind of new to Java, and for homework I got this exercise:
write a java program which can take a word from the keyboard and show it reversed
("hello" --> "olleh")
And this is how I wrote the program
import java.util.*;
import java.lang.*;
public class Inverti {
public static void main(String[] args) {
System.out.println("digiti una parola o una frase, essa sara' stampata a video alla rovescia");
Scanner tastiera = new Scanner(System.in);
String invertire = tastiera.nextLine();
for (int i = 0; i < invertire.length();) {
invertire.replace(invertire.charAt(i), invertire.charAt(invertire.length() - i));
i++;
}
System.out.print(invertire);
}
}
(I'm Italian, so consider that "tastiera" means "keyboard" and "digiti una parola o una frase, essa sarà stampata a video alla rovescia" means "type a word, it will be shown reversed")
The program gets compiled, but then, after typing the word:
exception in thread main java.lang.stringindexoutofboundsexception: string
index out of bounds: 6 (if string.length() is 6) or 5 (if string.length() = 5).
I looked for answers to other similar questions before posting, but nothing helped me, sorry if the question' s format maybe isn't right.
iis 0 at the first iteration. SocharAt(invertire.length()-i)will throw the exception.replacereturns a new String, you should assign the result.replace) does not modify THAT string but instead returns a new String which you must assign somewhere.