I am trying to create a code that takes any string and relays it back to me backwards missing every 3rd character and including the very last character.
EX: "123456789" should return "963" & "Hello, World!" should return "!r lH"
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i >= 0; --i) {
reverse = reverse + str.charAt(i - 3);
}
System.out.println(reverse);
}
}
The code above is what I have so far. However when I run this code I get this error message: "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
I don't understand because the string length is 10 so why is it not able to do this? Could someone explain this to me and give me a suggestion on how to fix this?
I suggest just iterating the characters in the string, starting from the last position, and moving backwards in increments of 3:
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
for (int i=str.length()-1; i >= 0; i=i-3) {
reverse += str.charAt(i);
}
System.out.println(reverse);
Your current approach is failing because the loop just takes single, not triple steps. Also note that you might want to use StringBuilder
instead of String
to build the reverse
string. This might be more efficient (though the JVM itself might substitute StringBuilder
on its own).