【问题标题】:Unknown cause of: java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 from Command Line未知原因:java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 from Command Line
【发布时间】:2019-10-24 14:47:48
【问题描述】:

由于某种原因,我收到了这个错误,此时我很困惑。 我该如何解决这个问题?

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)

【问题讨论】:

标签: java


【解决方案1】:

很明显,您在没有提供任何命令行参数的情况下运行了程序。因此,args 数组的长度为零。您的代码不是为应对它而设计的,它试图使用从数组末尾以外的位置获取的参数。

解决方案分为两部分:

  1. 您需要提供参数。例如,如果您从命令行运行程序:

      $ java name.of.your.mainclass filename
    
  2. 您需要修改程序,以便它检测到已在没有参数的情况下调用它并打印错误消息。例如:

    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);
    }
    

【讨论】:

  • 感谢您的回复。我尝试从命令行运行它并收到相同的错误。我认为我需要添加程序参数,这会解决我的问题吗?
  • 1) 如果你从命令行运行程序并且它给你同样的错误,你忘记包含文件名参数。 2) 提供论据可以解决部分问题。问题的另一部分是您应该修复代码,以便在用户不提供参数时不会引发异常。这只是糟糕的编程。一个错误。你应该修复它。
【解决方案2】:

您在运行程序时是否将任何参数传递给 main 方法?

你必须明确地将字符串传递给main(String[] args)中的args,否则args[0]会抛出异常

如何在eclipse中传递参数: Invoking Java main method with parameters from Eclipse

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2020-01-31
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多