0

I recently made a post saying that my code wasn't working and displayed the message:

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

with the code:

import java.util.Scanner;

public class FactorialProgram5 {

    public static void main(String args[]) {
        long n;
        long fact = 1;
        n = 1;
        
        for (int i = 1; i <= n; i++) {
            n = Long.parseLong(args[0]);
            fact = fact * i;
        }

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

Someone said I have to pass arguments to it and that the array is empty. What does it mean to pass an argument to the code? I am using eclipse, and someone told me that I have to go to the arguments tab and enter a value manually, but I need to make it so I can use this code in the command prompt too. How can I do this?

Ivo Mori
  • 2,177
  • 5
  • 24
  • 35
  • 1
    "I need to make it so I can use this code in the command prompt too" If you were using the command prompt, you would type the arguments in when you run the program. – khelwood Jul 16 '20 at 23:01

3 Answers3

1

Your main method is what takes any arguments from the command line. For example if you first navigate to the location of your java file on the command line: Type these commands. 1.javac filename.java this will compile your .java file 2. java filename (if you want to run without arguments). To pass arguments to your file use: java filename argument

Here argument is turned into a String array (args in the main method).

So when this file is compiled an then ran with something like the command java filename 99 the line n=Long.parseLong(args[0]); in your code will plug in the number 99 to args[0]. So n will get set to 99, or whatever you decide to type after java filename on the command line each time you run this program.

bdehmer
  • 569
  • 1
  • 6
  • 18
0

What that guy was talking about is that in the command line you can type in arguments when running the java program, kind of like this:

<run-java-using-a-command> Bob Joe Bill

I omitted the actual running since that isn't necessary if you're just going to use eclipse. But if you run it like this, then the args array will be this:

[Bob, Joe, Bill]

You can use those arguments in your program. In Eclipse, what you can do is click Run | Run | Program Arguments (on the top of the screen) to edit arguments.

Higigig
  • 1,175
  • 1
  • 13
  • 25
0

It means that you need to add a parameter on the command line so your program will find and process it. The parameter I am using in this example is the number 3.

I have compiled and run your program on the command line to show how it works.

$ javac FactorialProgram5.java
$ java FactorialProgram5 3    
fact=6
$

Note: I added a missing newline to the print instruction

System.out.print("fact=" + fact);

becomes

System.out.print("fact=" + fact + "\n");
jee
  • 26
  • 3