簡體   English   中英

我如何讓這個函數返回我正在尋找的值?

[英]How do I make this function return the value I'm looking for?

我創建了一個函數,用於遞歸計算函數中特定字符的數量。

public static int countCharInString(String s, char c)
    {

        return countCharInString(s, c, 0);


    }


    public static int countCharInString(String s, char c, int index)
    {
        if(index==s.length())
        {
            return 0;
        }
        if(s.charAt(index) == c)
        {
            return 1 + countCharInString(s, c, index+1);
        }
        if(s.charAt(index)!=c)
        {
            return countCharInString(s, c, index+1);
        }

    }

如何在函數的末尾放置一個 return 語句,該語句將返回我在函數內“計數”的整數?

在方法的末尾不需要額外的 return 語句,你得到的錯誤是因為編譯器不相信你已經涵蓋了所有情況。

最簡單的解決方法是簡單地將與c的第二個比較替換為else 字符等於c或不等於c ,您不需要單獨檢查。

例如

public static int countCharInString(String s, char c, int index) {
    if (index == s.length()) {
        return 0;
    }
    if (s.charAt(index) == c) {
        return 1 + countCharInString(s, c, index + 1);
    } else {
        return countCharInString(s, c, index + 1);
    }
}

我會使用 for 循環,如果需要遞歸,請檢查 Index+1 > s.length() 如果是這種情況,遞歸應該返回

您需要有一個參數來跟蹤您的運行總數。 向您的函數添加一個參數,每次找到該字符時都會增加該參數。 然后返回該數字而不是返回 0

在這里使用遞歸對我來說沒有意義。 字符串中的字符數將是`s.length()'。

但是,由於這是您的要求 - 我相信您想要一些字符的數量 - 我認為這是一個經典的“重新發明”輪子程序。 雖然我不喜歡這些,但重要的是了解正在發生的事情。

首先,您不需要索引變量...因為您總是將其設置為 0。所以只需使用 0。

其次,讓我們使用substring這樣我們就不必轉換為字符並處理字符/字符串比較等。

public static int countCharInString(String s, String c) {
  // This will only happen when the string is empty to begin with, our we're done with recursion. Since we add this to another number in recursion - it works for our purpose
  if (s.length() == 0) {
    return 0;
  }

  // If we have a match, increment add add to our recursive sum
  if ((s.substring(0, 1).equals(c))) {
    return 1 + countCharInString(s.substring(1), c);
  }

  // do the final return and invoke recursion
  return countCharInString(s.substring(1), c);
}

暫無
暫無

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

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