简体   繁体   中英

Java recursive method to print one word in a string at a time without loops

For this program, the idea is to print one word in a string at a time using a recursive method, assuming that there is only one word between spaces. When I run this program as is, however, it instead prints the string itself.

public static void stringByWords(String s) {


    if (s.isEmpty())

        return;

    if (s.indexOf(" ") == 1)

     stringByWords(s.substring(s.indexOf(" ") + 1) + "\n");

    System.out.println(s);


}//end stringByWords

I realize it would be a hell of a lot easier to do this as an iterative method with just a loop, but I'm required to use recursion as instructed. Any tips as to what I'm doing incorrectly will be appreciated.

The trick with recursion is to follow the standard pattern

func(context)
    if context is very simple
        process context
    else
        break context into several pieces
            call func on each piece

So for your case, the simple situation is a single words with no spaces. Otherwise break into two pieces and call on each piece:

void printWords(String str) {
    int space = str.indexOf(' ');
    if (space == -1) {
        System.out.println(str);
    } else {
        printWords(str.substring(0, space));
        printWords(str.substring(space + 1));
    }
}

Alright, after fixing up my code from the tips I was given, it seems to function as intended. I will put the fixed code here in case it is helpful to someone else. Thanks to those who had helped.

public static void stringByWords(String s) {

    int space = s.indexOf(' ');

    if (s.isEmpty()) //error case

        return;

    if (space == -1) { //base case

        System.out.println(s);
    }
    else { 

        stringByWords(s.substring(0, space));//recursive steps
        stringByWords(s.substring(space + 1));

    }//end else


}//end stringByWords

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM