-4

When I try to run and compile my code, the console shows:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at FactorialProgram5.main(FactorialProgram5.java:9)

I can't figure out why it is doing that as the other codes that I did are working.

Here is my code:

import java.util.Scanner;

public class FactorialProgram5 {
    public static void main(String args[]) {
        long n;
        long fact = 1;

        n = Long.parseLong(args[0]);

        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }

        System.out.print("fact=" + fact);
    }
}
  • It's working fine – bigbounty Jul 15 '20 at 23:43
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – akuzminykh Jul 15 '20 at 23:43

2 Answers2

0

If you are not passing an argument when execute the program, args[0] it tries to retrieve the first value of the array of arguments, but if the array is empty (because you didn't pass a value) it raise this kind of exception.

ArrayIndexOutOfBoundsException: 0 means that you tried to access a position that doesn't exist in the array. If you try to access the position 0 and it fails is because the array is empty.

John Doe
  • 13
  • 4
0

Because when you are running your program you are not passing arguments to it. The your args array is empty and when you are trying to get the 0th element of empty array you get IndexOutOfBoundException The following line expects argument

n=Long.parseLong(args[0]);

try to run your program by passing arguments to it

Oktay Alizada
  • 290
  • 1
  • 6
  • 19