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

Java递归统计字符串单词数:类设计与递归函数返回值困惑

解决Java递归统计单词数的返回值困惑及完整实现

针对你需要实现的Words类,这里提供两种符合要求的递归统计方案,解决你对递归返回值的困惑:

方案一:递归方法返回统计数,赋值给成员变量w

这种方式保留递归方法的返回值特性,将最终统计结果直接存入类的w成员中,代码实现如下:

import java.util.Scanner;

public class Words {
    private String text;
    private int w; // 单词总数

    // 构造方法
    public Words() {
        this.text = "";
        this.w = 0;
    }

    // 读取含多空格的句子
    public void accept() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入句子:");
        this.text = scanner.nextLine();
        scanner.close();
    }

    // 对外暴露的统计方法,将递归结果存入w
    public void findWords() {
        String trimmedText = text.trim();
        this.w = trimmedText.isEmpty() ? 0 : countWordsRecursively(trimmedText);
    }

    // 递归核心方法,返回当前子串的单词数
    private int countWordsRecursively(String str) {
        int spaceIndex = str.indexOf(' ');
        // 子串无空格,说明是最后一个单词,返回1
        if (spaceIndex == -1) {
            return 1;
        }
        // 跳过连续空格,定位下一个单词的起始位置
        int nextWordStart = spaceIndex;
        while (nextWordStart < str.length() && str.charAt(nextWordStart) == ' ') {
            nextWordStart++;
        }
        // 递归统计剩余子串,累加当前单词的计数(+1)
        return 1 + countWordsRecursively(str.substring(nextWordStart));
    }

    // 展示统计结果
    public void result() {
        System.out.println("句子中的单词总数为:" + this.w);
    }

    // 测试入口
    public static void main(String[] args) {
        Words words = new Words();
        words.accept();
        words.findWords();
        words.result();
    }
}

关键说明

  • 先对输入字符串做trim()处理,避免首尾空格导致的统计误差;
  • 递归方法countWordsRecursively专注于统计子串的单词数,通过返回值传递结果,最终由findWords方法将结果赋值给w;
  • 遇到连续空格时,跳过所有空格再递归处理剩余部分,避免重复计数。

方案二:递归方法直接更新成员变量w

如果不想使用递归返回值,也可以让递归方法直接操作类的w成员,代码如下:

import java.util.Scanner;

public class Words {
    private String text;
    private int w; // 单词总数

    public Words() {
        this.text = "";
        this.w = 0;
    }

    public void accept() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入句子:");
        this.text = scanner.nextLine();
        scanner.close();
    }

    public void findWords() {
        this.w = 0;
        String trimmedText = text.trim();
        if (!trimmedText.isEmpty()) {
            countWordsRecursivelyV2(trimmedText);
        }
    }

    // 递归方法直接更新w,无返回值
    private void countWordsRecursivelyV2(String str) {
        int spaceIndex = str.indexOf(' ');
        if (spaceIndex == -1) {
            this.w++;
            return;
        }
        // 找到一个单词,w加1
        this.w++;
        // 跳过连续空格
        int nextWordStart = spaceIndex;
        while (nextWordStart < str.length() && str.charAt(nextWordStart) == ' ') {
            nextWordStart++;
        }
        // 递归处理剩余子串
        countWordsRecursivelyV2(str.substring(nextWordStart));
    }

    public void result() {
        System.out.println("句子中的单词总数为:" + this.w);
    }

    public static void main(String[] args) {
        Words words = new Words();
        words.accept();
        words.findWords();
        words.result();
    }
}

关键说明

  • 递归方法为void类型,每找到一个有效单词就给w加1;
  • 统计前先重置w为0,避免多次调用findWords时数据残留;
  • 同样处理连续空格和首尾空格的边界情况。

两种方案都能满足你的需求,你可以根据自己对递归返回值的理解选择合适的实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:05:18