You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用递归方式统计Java字符数组单词数?现有代码问题修复

Fix Recursive Word Count Logic in Char Array (Using Provided Helpers, No String Conversion)

Hey there, let's tackle this word count issue you're facing. You're trying to recursively count words in a char array using two already implemented helper methods: trimLeadingSpaces(char[] array) (removes leading spaces) and idxFirstSpace(char[] array, int currentIdx) (finds the first space index starting from currentIdx). Right now, your countWords method has logic flaws—for example, input " abc " returns 2 instead of the expected 1. Also, you can't modify method signatures or convert the char array to a String, so we need to fix this with pure char array operations and recursion.

Current Problematic Code

public static int countWords(char[] array) {
    if (array == null) throw new IllegalArgumentException("The received array is null");
    char[] array_new = trimLeadingSpaces(array);
    //Arrays.copyOfRange(array_new, idxFirstSpace(array_new, 0), array_new.length);
    if(idxFirstSpace(array_new, 0) == 0) return 0;
    if(idxFirstSpace(array_new, 0) == array_new.length) return 1;
    return 0;
}

Test Cases & Expected Results

  • test_countWords("abc") → Expected: 1
  • test_countWords(" abc ") → Expected: 1 (but current code returns 2)
  • test_countWords(" abc def") → Expected: 2
  • test_countWords(" abc def d") → Expected: 3
  • test_countWords("a a def d g ") → Expected: 5
  • test_countWords(" ") → Expected: 0
  • test_countWords("") → Expected: 0
  • test_countWords(null) → Expected: IllegalArgumentException: The received array is null

What's Wrong with the Current Code?

Your current implementation doesn't use recursion at all—it only handles two edge cases and returns 0 for everything else. The core issue is missing recursive logic to count subsequent words, which leads to incorrect results for most non-trivial inputs.

Correct Recursive Implementation

Here's the fixed countWords method that follows the recursive approach and uses your helper methods correctly:

import java.util.Arrays;

public static int countWords(char[] array) {
    // Handle null input first
    if (array == null) {
        throw new IllegalArgumentException("The received array is null");
    }

    // Trim leading spaces to skip any leading whitespace
    char[] trimmedArray = trimLeadingSpaces(array);

    // If after trimming, the array is empty (all spaces originally), return 0
    if (trimmedArray.length == 0) {
        return 0;
    }

    // Find the first space in the trimmed array
    int firstSpaceIdx = idxFirstSpace(trimmedArray, 0);

    // If no space found, this is a single word
    if (firstSpaceIdx == trimmedArray.length) {
        return 1;
    }

    // Recursively count words in the subarray starting after the first space
    // The recursive call will handle trimming any leading spaces from the remaining array
    char[] remainingArray = Arrays.copyOfRange(trimmedArray, firstSpaceIdx, trimmedArray.length);
    return 1 + countWords(remainingArray);
}

Explanation of the Fix

  1. Null Handling: We keep the original null check to throw the required exception as specified.
  2. Trim Leading Spaces: Every time we start processing an array (or subarray), we first trim leading spaces—this ensures we don't count empty space as words and focuses on actual content.
  3. Empty Trimmed Array Check: If trimming leaves us with an empty array, that means there were no actual words, so we return 0.
  4. Single Word Check: If there's no space in the trimmed array, that's one complete word—return 1.
  5. Recursive Step: When we find the first space, we create a subarray starting from that space to the end of the trimmed array. We then recursively call countWords on this subarray (which will trim any leading spaces from the subarray, skipping the spaces after the first word) and add 1 to account for the current word we just identified.

Why This Fixes Your " abc " Issue

For input " abc ":

  1. trimLeadingSpaces returns "abc " (length 4).
  2. idxFirstSpace finds the space at index 3, which is not equal to the array length (4).
  3. We create a subarray from index 3 to 4: " ".
  4. Recursive call to countWords(" "):
    • trimLeadingSpaces returns an empty array (length 0), so returns 0.
  5. Total is 1 + 0 = 1, which matches the expected result.

This implementation will correctly handle all your test cases, following the recursive approach and adhering to your constraints.

内容的提问来源于stack exchange,提问作者Ruca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:41:15