Java代码while循环触发String index out of range错误求助
解决String Index Out of Range错误及状态机逻辑优化
问题根源分析
我一眼就看到两个导致错误的核心问题:
- 初始索引越界:程序启动时
i的初始值是0,第一次进入while循环时,你调用了s.charAt(i-1),也就是s.charAt(-1)——Java字符串的索引从0开始,负数索引直接触发StringIndexOutOfBoundsException,这就是你看到的错误。 - 混淆Java与C的字符串规则:你用
'\0'来判断字符串结束,这是C语言的老习惯,但Java的String内部根本不存在这个终止符!哪怕索引合法,这个判断也永远不会成立,最终会因为i持续递增超出字符串长度再次触发越界错误。
修复方案
我们需要彻底调整循环终止逻辑,同时优化一些冗余代码:
- 替换循环条件:用字符串长度作为终止判断,改成
while(i < s.length()),这样能安全遍历每个字符,不会越界。 - 移除无效初始化:你一开始写的
String s = new String(new char[20]);完全多余,因为后面用Scanner.nextLine()重新给s赋值了,直接删掉就行。 - 修正入口方法:原代码的
public static int Main()不符合Java规范,改成标准的public static void main(String[] args)才能让程序正常启动。
修改后的完整代码
import java.util.Scanner; public class StateMachineDemo { public static void main(String[] args) { String s; byte c; int state = 0; int i = 0; System.out.print("\n Enter a string:"); s = new Scanner(System.in).nextLine(); while (i < s.length()) { switch (state) { case 0: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 1; } else if (c == (byte)'b') { state = 2; } else { state = 6; } break; case 1: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 3; } else if (c == (byte)'b') { state = 4; } else { state = 6; } break; case 2: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 6; } else if (c == (byte)'b') { state = 2; } else { state = 6; } break; case 3: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 3; } else if (c == (byte)'b') { state = 2; } else { state = 6; } break; case 4: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 6; } else if (c == (byte)'b') { state = 5; } else { state = 6; } break; case 5: c = (byte) s.charAt(i++); if (c == (byte)'a') { state = 6; } else if (c == (byte)'b') { state = 2; } else { state = 6; } break; case 6: System.out.printf("\n %s is not recognised.", s); System.exit(0); } } if (state == 1) { System.out.printf("\n %s is accepted under rule 'a'", s); } else if ((state == 2) || (state == 4)) { System.out.printf("\n %s is accepted under rule 'a*b+'", s); } else if (state == 5) { System.out.printf("\n %s is accepted under rule 'abb'", s); } } }
额外说明
现在循环会安全遍历字符串的每一个字符,当i等于字符串长度时自动终止,完美解决了索引越界的问题;同时修正后的入口方法也能保证程序正常运行。
内容的提问来源于stack exchange,提问作者ehelp fit
相关产品推荐
相关产品推荐

