首页 > 解决方案 > 递归主方法中的 ArrayIndexOutOfBoundsException

问题描述

此代码用记事本编写并在命令提示符下运行。输入为computer is fun,输出为:

fun
is
computer

当我尝试在 NetBeans 中编写它时,它给了我一个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

有什么问题,如何获得与在命令提示符下运行它时相同的输出?

class A{
   public static void main(String[] args) {
    args[0]="Computer";
    args[1]="Science";
    args[2]="is";
    args[3]="fun";
      if (args.length>1)
      {
         String []newargs = new String [args.length-1];
         for (int i = 0 ; i<newargs.length ;i++)
         {
            newargs[i]=args[i+1];
         }

         main (newargs);
         //System.out.println(args.length);
      }
      System.out.println(args[0]);
      return;
   }
}

标签: javarecursionindexoutofboundsexception

解决方案


如果if-statement条件为真,您正在调用main(newargs).

这就是递归:当一个方法调用自己时。

这里的问题是for循环迭代直到i等于newargs.length-1然后,您尝试访问args[i+1]比数组中可用的索引多 1 个索引。

这是因为在 Java 中,数组是从 0 开始索引的:大小为 5 的数组的索引是 0-4。如果您尝试访问位于 的元素array.length,那将始终比可用元素多 1!

编辑:所以,为了使这项工作,将for循环上的边界条件更改为i<newargs.length-1,你不应该再得到ArrayIndexOutOfBoundsExceptions


推荐阅读