Reputation: 1
I get an error Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 80 at Factorial.fact<Factorial.java:32> and at <Factorial.main.java:5>
I'm not sure how to fix this program?
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;
}
}
Upvotes: 0
Views: 1893
Reputation: 285405
What's going to happen here:
for(int d=0;d<product.length;d++)
{
product[d+1]=product[d+1]+(product[d]/10);
product[d]=product[d]%10;
}
when d == product.length - 1
? specifically here product[d+1]
An index out of bounds error since here d + 1 is beyond the allowed indexes for the product array.
Upvotes: 3