-2

I want to write this little program which should make a simple calculation while taking input for one variable. Here's the code:

public class DFact {
    public static void main(String[] args) {
        int n;
        int df;
        int i;

        n = Integer.parseInt(args[0]);  
        df = 1;                 
        i = n;              

        while(i > 0) {
            df = df * i;        
            i = i - 2;          
        }

        System.out.println(df); 
     }
}

For this programm I am getting the following message:

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

Lukas Schroll
  • 15
  • 1
  • 1
  • 6
    How are you passing in the argument? This suggests that you aren't passing any arguments to the program. Can you show what you're using to start it and how it's set up? – Brian Aug 18 '17 at 16:34
  • 2
    The question title asks about `Double.parseDouble` but the code has `Integer.parseInt`. Please try to be consistent. Anyway, as @Brian already said, probably you're not passing any argument, then `args` is empty, so you can't access `args[0]` as it doesn't exist. Maybe [this link](https://stackoverflow.com/q/890966/7605325) can help. –  Aug 18 '17 at 16:44

2 Answers2

2

I recommend you change your code to something like this:

public class DFact {
    public static void main(String[] args) {
        int n;
        int df;
        int i;

        for (String arg : args) { // to prevent nullpointers and index out of bound
            n = Integer.parseInt(arg);
            df = 1;
            i = n;

            while (i > 0) {
                df = df * i;
                i = i - 2;
            }

            System.out.println(df);
        }
    }
}

Then open a command line in the directory of you file and type:

javac {fileName.java} 

And

java {fileName} 1 2 3 4 5 6 
Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29
1

You're getting an index out of bounds exception, which means that there is no index 0 in args. Check the length of args before you request variables from it.

public class DFact
{
    public static void main(String[] args)
    {
        if (args.length > 0) {
            int n;              
            int df;                 
            int i;  

            n = Integer.parseInt(args[0]);  
            df = 1;                 
            i = n;              

            while(i > 0)            
            {
                df = df * i;        
                i = i - 2;          
            }

             System.out.println(df); 
        }
    }
}
anomeric
  • 688
  • 5
  • 17