I am currently working on a program that manipulates strings passed in as parameters using strictly recursion. Right now, I am stuck trying to print the word out vertically.

public static void printVertical(String str) {
      if (str == null || str.equals("")) {
      } else {
         char nextLetter = printVertical(str.substring(1));

This is the code for the method to print words vertically; the error I get when I try testing this method reads

java.lang.StringIndexOutOfBoundsException: String index out of range: 100
at java.lang.String.charAt(Unknown Source)
at StringRecursion.printVertical(StringRecursion.java:97)

I think it has something to do with the fact that my method returns void (something I'm not allowed to change due to assignment restrictions), and not char. Any help in guiding me in the right direction would be greatly appreciated.

Well, you are doing your recursion wrong. Do you really want to recurse before printing the first character (which you're not doing anyway since the recursive method doesn't return anything), and then recurs again?

You need to println charAt(0), then recurs substring(1)

Recursion is a bad idea here. But if this is what you want :

String str = "vertical";

and if the output should be :


Then your code shouldn't be hard.

do something like this :

static void printVertical(String s, int index)
    //check for error in index i.e check its bounds
   //print out string at location, index
   //recurse with s passed and index+1

Edited 7 Years Ago by firstPerson: n/a

This article has been dead for over six months. Start a new discussion instead.