簡體   English   中英

使用遞歸查找 java 中字符串中存在的單詞數

[英]finding number of words present in the string in java using recursion

一個class的話定義了一個遞歸的function來進行字符串相關的操作。 class詳情如下:

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.

我試過這段代碼

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));
}

但我需要返回一個 integer 值,我對此感到困惑..

在您的代碼中,最后一個 return 語句是不可訪問的。 原因:您已經放置了一個 if-else 塊,並在兩種情況下都放置了 return。 因此 function 實際上是從 if-else 塊本身返回的(在 else 中,if 的條件始終為真,因為您分配了這個值,即 str.indexOf(" "))。

我已經根據你上面給出的問題寫下了代碼......

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);
}

希望你覺得它工作得很好。

您的 function 已經返回 integer,它恰好始終為 0。這是由於

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

始終為真,c++ 僅在返回語句通過后更新。 發生這種情況是因為您已經將 i 設置為 indexOf(" ") 並且由於使用 int++ 實現了遞增。 另外,請記住,您需要將此處的單詞數增加 2,因為您要在兩個單詞之間結束 function。

因此,改用它:

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

您應該看到現在 function 正在返回正確數量的單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM