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

Java实现字符按指定次数重复功能报字符串索引越界错误排查

问题诊断
  • 核心报错原因:内层遍历数字的while循环未增加索引边界判断i < len,当索引走到字符串长度值时,仍会调用str.charAt(i)访问超出索引范围的位置,直接触发字符串索引越界异常。
    以你给出的输入a1b4c3(长度为6,有效索引范围0~5)为例:处理到最后一位数字3时,索引i从5自增到6,此时内层循环仍会执行Character.isDigit(str.charAt(6))的判断,直接访问了不存在的索引位置,触发报错。
  • 额外问题:原代码未导入java.util.Scanner包,会先出现编译错误;同时没有输入格式校验逻辑,遇到非字母开头、字母后无数字的非法输入时,会出现逻辑异常。
修复方案

修改后的可运行代码如下:

import java.util.Scanner;

public class StringMultiply {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String str = s.next();
        int len = str.length();
        int i = 0;
        String currentChar = "";
        while (i < len) {
            // 校验当前位为字母
            if (Character.isAlphabetic(str.charAt(i))) {
                currentChar = String.valueOf(str.charAt(i));
                i++;
            } else {
                throw new IllegalArgumentException("输入格式错误,必须以字母开头");
            }
            StringBuilder numStr = new StringBuilder();
            // 内层循环先判断索引边界,再校验是否为数字
            while (i < len && Character.isDigit(str.charAt(i))) {
                numStr.append(str.charAt(i));
                i++;
            }
            // 校验字母后存在数字
            if (numStr.length() == 0) {
                throw new IllegalArgumentException("输入格式错误,字母后必须跟随数字");
            }
            int count = Integer.parseInt(numStr.toString());
            System.out.print(currentChar.repeat(count));
        }
        s.close();
    }
}

核心修改点:

  1. 补充java.util.Scanner导包语句,修复编译问题
  2. 内层遍历数字的循环增加i < len边界判断,从根源避免索引越界
  3. 增加输入格式校验逻辑,遇到非法输入抛出明确提示,避免非预期输出
  4. 用StringBuilder替代String拼接数字字符串,提升执行性能
  5. 补充Scanner资源关闭操作,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:48:00