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(); } }
核心修改点:
- 补充
java.util.Scanner导包语句,修复编译问题 - 内层遍历数字的循环增加
i < len边界判断,从根源避免索引越界 - 增加输入格式校验逻辑,遇到非法输入抛出明确提示,避免非预期输出
- 用
StringBuilder替代String拼接数字字符串,提升执行性能 - 补充
Scanner资源关闭操作,避免资源泄漏
内容的提问来源于stack exchange,提问作者tinu
相关产品推荐
相关产品推荐

