java.lang.StringIndexOutOfBoundsException?

时间:2014-03-18 20:56:19

标签: java string exception replace

每次运行此程序时,我都会收到java.lang.StringIndexOutOfBoundsException。我不知道为什么。该程序应该将模式(a)_n转换为/ pochhammer {a} {n}。谢谢。

File file = new File("KLSadd.tex");
    Scanner scanner = new Scanner(file);
    PrintWriter writer = new PrintWriter("ConvertedPochhammer.tex");
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        char toChecko=')';
        for(int i=line.length();i>=0;i-- ){
            if(line.charAt(i)==toChecko&&line.charAt(i+1) == '_'){
                String substring = line.substring(0,i);
                int openParen = checkNestedParen(substring);
                String a = line.substring(openParen, i);
            if(line.charAt(i+2)=='{'){
                int startBracker = i+2;
                int endBracker = line.indexOf('}',i+2);
                String n = line.substring(startBracker, endBracker);
                line = line.substring(0, openParen) + "//pochhammer{" + a + "}{" + n + "}";
            }
            else {
                char n = line.charAt(i+2);
                line = line.substring(0, openParen) + "//pochhammer{" + a + "}{" + n + "}";
            }
            }
        }
        writer.println(line);
}
    writer.close();

1 个答案:

答案 0 :(得分:2)

请尝试int i = line.length() - 1作为循环起始值。

请记住,字符串索引(与Java中所有数组的情况一样)基于零。

Java运行时发出的极其全面的消息总是值得一读。