如何用递归方式统计Java字符数组单词数?现有代码问题修复
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: 1test_countWords(" abc ")→ Expected: 1 (but current code returns 2)test_countWords(" abc def")→ Expected: 2test_countWords(" abc def d")→ Expected: 3test_countWords("a a def d g ")→ Expected: 5test_countWords(" ")→ Expected: 0test_countWords("")→ Expected: 0test_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
- Null Handling: We keep the original null check to throw the required exception as specified.
- 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.
- Empty Trimmed Array Check: If trimming leaves us with an empty array, that means there were no actual words, so we return 0.
- Single Word Check: If there's no space in the trimmed array, that's one complete word—return 1.
- 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
countWordson 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 ":
trimLeadingSpacesreturns"abc "(length 4).idxFirstSpacefinds the space at index 3, which is not equal to the array length (4).- We create a subarray from index 3 to 4:
" ". - Recursive call to
countWords(" "):trimLeadingSpacesreturns an empty array (length 0), so returns 0.
- 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

