Java 奇怪的IndexOutofBoundSexcexception?
为什么会有IndexOutofBoundsException?似乎并没有变量表明索引可能超出范围。这个程序应该转换模式。这可能与我如何读取文件有关吗?谢谢Java 奇怪的IndexOutofBoundSexcexception?,java,string,exception,indexoutofboundsexception,Java,String,Exception,Indexoutofboundsexception,为什么会有IndexOutofBoundsException?似乎并没有变量表明索引可能超出范围。这个程序应该转换模式。这可能与我如何读取文件有关吗?谢谢 static int checkNestedParenFront(String line){ int count=0; for(int i=0;i<line.length();i++ ){ if(line.charAt(i)=='(') count++; if(
static int checkNestedParenFront(String line){
int count=0;
for(int i=0;i<line.length();i++ ){
if(line.charAt(i)=='(')
count++;
if(line.charAt(i)==')'&&count==0)
return i;
if(line.charAt(i)==')')
count--;
}
return 0;
}
String line = new String(Files.readAllBytes(Paths.get("new.txt")));
PrintWriter writer = new PrintWriter("old.txt");
while(line.contains("F_4")){
while(line.contains("$F_4$")) {
line=line.replace("$F_4$", "$\\AppellFiv");
}
int posAppell = line.indexOf("F_4");
int posSemi = line.indexOf(';', posAppell);
posSemi = line.indexOf(';', posSemi);
int posComma = line.indexOf(',', posSemi);
String check = line.substring(posComma+1);
int i = checkNestedParenFront(check);
String lastAppel = line.substring(posComma, i);
String beforeAppel=line.substring(0, posComma);
String afterAppel = line.substring(i+1);
line = line.replaceAll("F_4[^(]*\\(([^,]+),([^;]+);([^,]+),([^;]+);([^,]+),", "\\AppellFiv@{$1}{$2}{$3}{$4}{$5}");
line = beforeAppel + "{" + lastAppel + "}" + afterAppel;
}
static int checkNestedParenFront(字符串行){
整数计数=0;
对于(int i=0;i您的问题是,当您调用checkNestedParenFront(check)
时,您返回的是最后一个括号的check
中的计数,这与行中的计数不同,因为check
从行开始
然后,当您调用line.substring(posComma,i)
时,您的i
小于posComma
,这会导致异常
我想你的意思是有行。子字符串(posComma,posComma+I+1)
-但我不太确定+1
,因为不清楚你到底想实现什么。你应该能够告诉我们异常出现在哪一行。哪一行是异常?int posComma=line.indexOf(',',posSemi);String check=line.substring(posComma+1);
如果您输入abc,d,
@DavidWallace它是这一行:String lastAppel=line.substring(posComma,i);那么,如果posComma
的值是==line.length()-1
,您将得到该错误。