0

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.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by firstPerson
0

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)

0

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
}

Edited by firstPerson: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.