简体   繁体   English

线程“ main”中的异常

[英]Exception in the thread “main”

Hello when I'm trying to run this code I'm getting following error I understand this happens when there is no main function, however I do have a main fuction.. 您好,当我尝试运行此代码时,我遇到以下错误,我知道没有主要功能时会发生这种情况,但是我确实有主要功能。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FilterAs.main(FilterAs.java:21)

Here's my code 这是我的代码

  import java.io.*;
public class FilterAs {
public static int numberOfFiles(File directory) {  
      if (directory.isFile())  
         return(1);  
      else {  
         File[] list = directory.listFiles();  

         int count = 0;  

         if (list != null)  
            for (File file : list)  
               count += (file.isFile()) ? 1 : numberOfFiles(file);  

         return(count);  
      }  
   }  

   public static void main(String[] args) {  
      System.out.println(numberOfFiles(new File(args[0])));  
   }  

}  

I guess you forgot to set arguments for your program? 我想您忘记为程序设置参数了吗?

You are accesing the arguments when calling the method (numberOfFiles). 调用方法(numberOfFiles)时要访问参数。

If there are no command line arguments passed to the program, the following would throw ArrayIndexOutOfBoundsException since the args array would be empty. 如果没有命令行参数传递给程序,则由于args数组为空,因此以下内容将引发ArrayIndexOutOfBoundsException

System.out.println(numberOfFiles(new File(args[0])));  

You should check for the existence of such arguments before accessing the args array : 您应该在访问args数组之前检查是否存在此类参数:

if (args.length > 0) {
    System.out.println(numberOfFiles(new File(args[0])));  
} else {
    System.out.println("Please supply a file name"); 
}

You have a call to: 您可以拨打以下电话:

args[0]

But args is empty. 但是args是空的。

You have called your program with something like: 您已使用以下方式调用了程序:

java -jar MyJar.jar

But you should have called it with: 但是您应该用以下方式调用它:

java -jar MyJar.jar /a/path/to/some/directory

ie you need to pass an argument to your application. 也就是说,您需要将参数传递给您的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM