如何解决字符串索引越界异常?猜字游戏代码报错求助
猜字游戏(Hangman)字符串索引越界问题修复
错误原因分析
- 循环边界错误:
updateClue方法中循环条件i <= l会触发索引越界。字符串索引从0开始,长度为l的字符串最大有效索引是l-1,当i=l时,word.charAt(i)和clue.charAt(i*2)都会超出字符串的索引范围。 - 初始字符串多余空格:
update初始化为" "会导致最终提示串开头多出无效空格,同时加剧索引计算的错误风险。 - 格式一致性缺失:原代码中更新提示串时,匹配到字母的情况没有添加空格,会破坏
makeClue生成的"_ _ "格式,导致后续索引计算全部错位。
修复后的代码
修正核心方法
private String makeClue(String word) { int length = word.length(); String clue = ""; for(int i = 0; i < length ; i++) { clue += "_ "; } return clue; } private String updateClue(String clue, String word, String letter) { String update = ""; // 移除初始多余空格 char guess = letter.charAt(0); int l = word.length(); // 修正循环条件为i < l,避免越界 for(int i = 0; i < l; i++) { if(word.charAt(i) == guess) { update += guess + " "; // 保持和初始提示一致的“字符+空格”格式 } else { int index = i * 2; char thing = clue.charAt(index); update += thing + " "; } } return update; }
性能优化建议
频繁使用+=拼接字符串会重复创建对象,建议改用StringBuilder提升效率:
private String makeClue(String word) { int length = word.length(); StringBuilder clue = new StringBuilder(); for(int i = 0; i < length ; i++) { clue.append("_ "); } return clue.toString(); } private String updateClue(String clue, String word, String letter) { StringBuilder update = new StringBuilder(); char guess = letter.charAt(0); int l = word.length(); for(int i = 0; i < l; i++) { if(word.charAt(i) == guess) { update.append(guess).append(" "); } else { int index = i * 2; char thing = clue.charAt(index); update.append(thing).append(" "); } } return update.toString(); }
内容的提问来源于stack exchange,提问作者PHOEBE COMBS
相关产品推荐
相关产品推荐

