-2
class Factorl
{
    public static void main(String args[])

    {
              long n,fact=1;       

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

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

          System.out.println("fact="+fact);
    }
}

its showing Exception in thread "main"

java.lang.ArrayIndexOutOfBoundsException: 0 at Factorl.main

MangduYogii
  • 935
  • 10
  • 24

2 Answers2

0

Because you using command-line arguments as an input in your program line

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

Here you should pass a value for running a program like this

  compile by > javac Factorl.java  
   run by > java Factorl 5

    Output:
    fact=120
MangduYogii
  • 935
  • 10
  • 24
0

Your args array could be empty if nothing is passed to it (ref). Make a check for its emptiness.

class Factorl {
    public static void main(String args[]) {
        long n, fact = 1;
        if (args.length != 1) {
            System.out.println("Factorial for what?");
            return;
        }
        n = Long.parseLong(args[0]);
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }
        System.out.println("fact=" + fact);
    }
}

I do not personally think that you would be calculating the factorial of a Long. The factorials grow very quickly. Note that 20! is 2.432902e+18. Thats at huge number. Now you can refer @MangduYogii's answer for "How to pass command line arguments".

Prashant
  • 4,775
  • 3
  • 28
  • 47