Home > Enterprise >  finding number of words present in the string in java using recursion
finding number of words present in the string in java using recursion

Time:12-28

A class words defines a recursive function to perform string related operations. The class details are given below:

Class name : words
Data members/instance variables
 text : to store string.
 w : integer variable to store total words.
Member functions/methods
 words( ) : constructor to store blank to string and 0 to integer data.
 void Accept( ) : to read a sentence in text. Note that the sentence may contain more
 than one blank space between words.
 int FindWords(int) : to count total number of words present in text using Recursive
 Technique and store in ‘w’ and return.
 void Result( ) : to display the original string. Print total number of words stored in
 ‘w’ by invoking the recursive function.

I tried this code

public static int CountWords(String str) {
    int c = 0;
    int i = str.indexOf(" ");
    if (str.isEmpty()) {
        return 0;
    }else 
        if (i == str.indexOf(" ")) {
      return c  ;
   }
  //str.substring(0,str.indexOf(" ")-1);
    c  ;
    return c   CountWords(str.substring(i   1));
}

but i need to return an integer value and i am confused with that..

CodePudding user response:

In your code, the last return statement is inaccessible. Reason: you have put an if-else block and have put return in both the cases. So the function actually gets returned from the if-else block itself (within else, the condition of if is always true since you assigned the very value i.e. str.indexOf(" ")).

I have written down the code according to the question you gave above...

public int findWords(int i){
    if(i > text.lastIndexOf(" "))
        return 1;
    i = text.substring(i).indexOf(" ")   i;
    if(i < 0)
        return 1;
    if(text.substring(i).equals(null))
        return 0;
    return( findWords(i 1)   1);
}

Hope you find it well working.

CodePudding user response:

Your function already is returning a integer, it just happens to always be 0. This is due to

else if (i == str.indexOf(" ")) {
  return c  ;
}

Always being true and c only updating after the return statement was passed. This happens because you already set i to be the indexOf(" ") and due to the implementation of incrementation using int . Also, keep in mind hat you need to increase the number of words by 2 here, since you're ending the function between two words.

Therefore, use this instead:

else if (i == str.lastIndexOf(" ")) {
  return c 2;
}

You should see that now the function is returning the correct amount of words.

  • Related