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("")) {
         System.out.print("");
      } else {
         char nextLetter = printVertical(str.substring(1));
         System.out.println(nextLetter);
         printVertical(str);
      }
   }

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";
printVertical(str);

and if the output should be :

v
e
r
t
i
c
a 
l

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
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.