我正在尝试在 Eclipse 中制作 Java 代码的 AST。
作为链接的示例,我编写代码来创建示例 AST
但是,运行代码后,我有 ArrayIndexOutOfBoundsException 错误。
完整的代码和错误信息附在下面
有谁知道为什么会发生这个错误?
我的代码
import java.util.Map;
import org.eclipse.jface.text.Document;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class ASTtest {
static String src = "public class Sample {\r\n" +
" public static void main(String[] args){\r\n" +
" case1();\r\n" +
" case2();\r\n" +
" case3();\r\n" +
" }\r\n" +
" static void case1(){\r\n" +
" int a = 1000;\r\n" +
" int b = 10000;\r\n" +
"\r\n" +
" for (int i = 0; i <100 ; i++) {\r\n" +
" if(a<i){\r\n" +
" a=i;\r\n" +
" }else{\r\n" +
" b--;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" static void case2(){\r\n" +
" int a = 1000;\r\n" +
" int b = 10000;\r\n" +
" for (int i = 0; i <1000 ; i++) {\r\n" +
" if(a<i){\r\n" +
" a=i;\r\n" +
" }else{\r\n" +
" b--;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" static void case3(){\r\n" +
" int a=0;\r\n" +
" int b=120847;\r\n" +
" while(a==10000){\r\n" +
" a++;\r\n" +
" b--;\r\n" +
" b+=200;\r\n" +
" for (int i = 0; i <1000 ; i++) {\r\n" +
" a+=1;\r\n" +
" a-=1;\r\n" +
" int k =1;\r\n" +
" while(k <10000){\r\n" +
" k++;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" for (int i = 0; i < 900; i++) {\r\n" +
" a++;\r\n" +
" for (int j = 0; j <100 ; j++) {\r\n" +
" a--;\r\n" +
" a++;\r\n" +
" }\r\n" +
" a--;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"";
public static void main(String[] args) {
char[] source = src.toCharArray();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(source);
Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
CompilationUnit result = (CompilationUnit) parser.createAST(null);
}
}
错误信息
> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11671)
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11924)
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11881)
at org.eclipse.jdt.internal.compiler.parser.Parser.dietParse(Parser.java:10286)
at org.eclipse.jdt.core.dom.CompilationUnitResolver.parse(CompilationUnitResolver.java:535)
at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1227)
at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:823)
at ASTtest.main(ASTtest.java:78)
在错误消息中,问题行(ASTtest.java:78)是这个
CompilationUnit result = (CompilationUnit) parser.createAST(null);