我正在尝试理解Java Code,它在编译索引超出范围时会出错。我试图弄清楚为什么它会给出这个错误但是失败了。任何人都可以帮助我,为什么这段代码给出了索引超出范围的错误?
try {
ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb
.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
ProfilerServant profilerServant = new ProfilerServant(args[4],
args[5].equals("true"));
org.omg.CORBA.Object ref = rootpoa
.servant_to_reference(profilerServant);
Profiler pref = ProfilerHelper.narrow(ref);
org.omg.CORBA.Object objRef = orb
.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
String name = "Profiler";
NameComponent path[] = ncRef.to_name(name);
ncRef.rebind(path, pref);
orb.run();
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace(System.out);
}
}
这是ProfilerServant类 使用构造函数
public class ProfilerServant extends ProfilerPOA {
boolean cacheEnabled;
ServerParser parser;
HashMap<String, Integer> songCache;
HashMap<String, User> userCache;
ProfilerServant(String fileName, boolean cacheEnabled) {
this.cacheEnabled = cacheEnabled;
parser = new ServerParser(fileName);
songCache = new HashMap<String, Integer>();
userCache = new HashMap<String, User>();
init();
}
答案 0 :(得分:2)
java应用程序的入口点是main
方法。
public static void main(String[] args){}
args
是用于运行程序的命令行参数的String
数组。
假设您的主要班级是Program.java
。
在终端或命令提示符下,使用javac Program.java
编译程序并使用java Program /filename true
args
数组是:"java","Program","/filename","true"
鉴于ProfilerServant(String fileName, boolean cacheEnabled)
,您可以将ProfilerServant
实例化为:
ProfilerServant profilerServant = new ProfilerServant(args[2],
args[3].equals("true"));
//This turns to:
ProfilerServant profilerServant = new ProfilerServant("/filename",
"true".equals("true"));
尝试访问超出args
范围的索引将导致IndexOutOfBounds
。
答案 1 :(得分:-1)
代码将args传递给profilerServant类构造函数。 确保args [4]和args [5]的值的初始化是正确的。 检查参数args的长度[4]。