【问题标题】:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 80线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:80
【发布时间】:2016-01-17 18:57:58
【问题描述】:

我在线程“main”中得到一个错误异常

java.lang.ArrayIndexOutOfBoundsException: 80 at Factorial.fact<Factorial.java:32> and at <Factorial.main.java:5>

我不确定如何修复这个程序?

class Factorial
{
   public static void main(String[] args)
   {
     int[] a=fact(0);
     int[] b=fact(1);
     int[] c=fact(5);
     int[] d=fact(50);   
     System.out.println("zero factorial  = ");   
     for(int i=0;i<a.length;i++)
        System.out.println(fact(i));
     System.out.println("one factorial   = ");
     for(int j=0;j<b.length;j++)
        System.out.println(fact(j));
     System.out.println("five factorial  = ");
     for(int k=0;k<c.length;k++)
        System.out.println(fact(k));
     System.out.println("fifty factorial = ");
     for(int l=0;l<d.length;l++)
        System.out.println(fact(l));
  }
  public static int[] fact(int n)
  {
     int[] product=new int[80];
     for(int a=1; a<product.length;a++)
        product[a]=0;
     product[0]=1;
     for(int b=2,c=0; b<=n;b++,c++)
        product[c]=product[c]*b;
     for(int d=0;d<product.length;d++)
     {
        product[d+1]=product[d+1]+(product[d]/10);
        product[d]=product[d]%10;
     }
     return product;
  }
}

【问题讨论】:

  • product[d+1] 看起来像是罪魁祸首。
  • 作为开始格式化会有所帮助。除此之外,它可能是这个product[d+1]。循环定义为for(int d=0;d&lt;product.length;d++),因此当d 变为79 时,product[d+1] 将导致product[80],因此索引将超出范围(0-79)。
  • 感谢您的帮助。您建议如何解决此问题?

标签: java arrays exception indexoutofboundsexception


【解决方案1】:

这里会发生什么:

 for(int d=0;d<product.length;d++)
 {
    product[d+1]=product[d+1]+(product[d]/10);
    product[d]=product[d]%10;
 }

什么时候d == product.length - 1?特别是这里product[d+1]

索引超出范围错误,因为此处 d + 1 超出了产品数组的允许索引。

【讨论】:

  • 非常感谢。你知道我如何在没有所有前导零的情况下打印阶乘吗?
猜你喜欢
  • 1970-01-01
  • 2012-01-13
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多