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

我的Java程序‘Teen talk’无限加载请求排查(CodeHS环境)

问题分析与修复

你的程序一直处于加载状态,核心原因是死循环,问题出在teenTalk方法里的while循环:

当sentence.charAt(i)不是空格时,这个while会无限执行——它不断把同一个字符追加到result中,但i的值完全没有变化,永远满足sentence.charAt(i) != ' '的条件,循环根本停不下来。

修复方案

调整逻辑为逐个遍历字符串的每个字符:遇到空格就追加"like ",否则直接将当前字符加入结果。另外注意,原代码的run方法仅调用了teenTalk但未打印结果,建议添加输出语句才能看到运行效果。

修正后的基础版本

public class Scratchpad extends ConsoleProgram
{
    public void run()
    {
        // 测试并打印结果
        System.out.println(teenTalk("This is so cool"));
    }

    public String teenTalk(String sentence)
    {
        String result = "";
        
        for(int i = 0; i < sentence.length(); i++)
        {
            char currentChar = sentence.charAt(i);
            // 先加入当前字符
            result += currentChar;
            // 如果是空格,追加"like "
            if(currentChar == ' ')
            {
                result += "like ";
            }
        }
        return result;
    }
}

更高效的版本(使用StringBuilder)

如果处理较长的字符串,用StringBuilder比直接拼接String性能更好,CodeHS平台也支持这个类:

public class Scratchpad extends ConsoleProgram
{
    public void run()
    {
        System.out.println(teenTalk("This is so cool"));
    }

    public String teenTalk(String sentence)
    {
        StringBuilder result = new StringBuilder();
        
        for(int i = 0; i < sentence.length(); i++)
        {
            char currentChar = sentence.charAt(i);
            result.append(currentChar);
            if(currentChar == ' ')
            {
                result.append("like ");
            }
        }
        return result.toString();
    }
}

运行后,输入"This is so cool"会输出:This like is like so like cool,符合你想要的青少年说话风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:35:21