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

开发移除元音的压缩程序出现StringIndexOutOfBoundsException错误求助

报错根源分析
  • 直接触发StringIndexOutOfBoundsException的原因是循环首次执行时的索引调用逻辑:你的循环变量i从0开始遍历,首次进入循环时i=0,此时msg.charAt(i-1)等价于msg.charAt(-1),字符串索引从0开始计数,传入负数索引必然触发越界异常。
  • 现有逻辑和你提到的「移除元音」需求不匹配:你当前的判断条件使用了逻辑或||,只要满足「不是元音」或者「前一位是空格」就会保留字符,也就是说如果元音出现在空格之后,会被直接保留,不符合移除所有元音的要求。
修复代码

方案1:实现移除所有元音的需求(符合你描述的作业要求)

static String stringCompress(String msg) {
    String output = "";
    for (int i = 0; i < msg.length(); i++) {
        char currentChar = msg.charAt(i);
        // 仅保留非元音字符即可,无需判断前一位字符
        if (!VOWELS.contains(String.valueOf(currentChar))) {
            output += currentChar;
        }
    }
    return output;
}

方案2:如果你实际需求是保留空格后的元音,仅移除非空格后的元音

需要先对i=0的边界情况做判断,避免访问负索引:

static String stringCompress(String msg) {
    String output = "";
    for (int i = 0; i < msg.length(); i++) {
        char currentChar = msg.charAt(i);
        // 先判断i是否大于0,再访问前一位索引,避免越界
        boolean previousIsWhitespace = i > 0 && Character.isWhitespace(msg.charAt(i-1));
        if (!VOWELS.contains(String.valueOf(currentChar)) || previousIsWhitespace) {
            output += currentChar;
        }
    }
    return output;
}

注:以上实现均严格遵循你要求的使用String而非数组的实现规则,未引入数组操作。如果输入字符串长度较大,String拼接会产生较多临时对象,性能弱于StringBuilder,但符合你的实现要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:09:05