由于某种原因,我收到此错误,此时我非常困惑。 如何更正此问题?
public static void main(String[] args) throws FileNotFoundException {
Memory myMemory = new Memory();
File file = new File(args[0]);
myMemory.fileParser(file);
}
这是我的错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Memory.main(Memory.java:262)
很明显,您在没有提供任何命令行参数的情况下运行了该程序。 因此,args
arraay 的长度为零。 您的代码不是为了应对它而设计的,它试图使用从数组末尾以外的位置获取的参数。
该解决方案分为两部分:
-
您需要提供参数。 例如,如果从命令行运行程序:
$ java name.of.your.mainclass filename
-
您需要修改程序,以便它检测到它已被调用而不带参数并打印错误消息。 例如:
public static void main(String[] args) throws FileNotFoundException { if (args.length != 1) { System.err.println("Filename argument missing.") System.err.println("Usage: <command> <filename>"); System.exit(1); } Memory myMemory = new Memory(); File file = new File(args[0]); myMemory.fileParser(file); }
运行程序时,您是否将任何参数传递给 main 方法?
你必须在main(String[] args)
中将字符串显式传递给 args,否则args[0]
会抛出异常
如何在日食中传递参数: 使用 Eclipse 中的参数调用 Java main 方法