-1

I am getting a java.lang.StringIndexOutOfBoundsException whenever I run this program. I am not sure why. This program is supposed to convert a pattern (a)_n into /pochhammer{a}{n}. Thanks.

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();
user2825125
  • 81
  • 1
  • 12
  • 3
    You're not sure why you get a StringIndexOutOfBoundsException?? Could it be because your string index is out of bounds? Could it be that if you look at the exception traceback you will be directed to the exact line where the failure occurred?? Could it be that if you insert System.out.println calls you can figure out what the string index and string length are at the point of failure?? ?? Nah! – Hot Licks Mar 18 '14 at 20:59
  • 1
    A bit abusive but correct. Looking at your stacktrace should point out the problem pretty well. In any future questions you should also include a stacktrace if your program generates one. – indivisible Mar 18 '14 at 21:01

2 Answers2

2

Try int i = line.length() - 1 instead as your loop starting value.

Remember that string indexing (as is the case of all arrays in Java) is zero based.

The extremely comprehensive messages that the Java runtime emits are always worth reading.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

You are mixing up length and index:

"length 8"
index 7 ^

"first one"
 ^ index 0
indivisible
  • 4,892
  • 4
  • 31
  • 50