1

I am a new programmer in my first Java class . Here is my code but I am getting an error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0 at CmdLine.main(CmdLine.java:13)


import java.util.Scanner;
import java.util.Arrays;

public class CmdLine{
 public static void main( String [] args ){
   int[] array;
   array = new int [ 10 ];
   for(int counter = 0; counter < array.length;counter++ )
      array[counter]=Integer.parseInt (args[counter]);
      System.out.printf( "%s%8s\n", "Index", "Value" );

      for(int counter = 0; counter < array.length; counter++ )
         System.out.printf( "%5d%8d\n", counter, array[ counter ] );
   }
 }

Amol Raje
  • 928
  • 3
  • 9
  • 16
Andy
  • 11
  • 2

1 Answers1

0

There are many approaches to solve this.

- Methods:

I know most IDEs allow you to add command line arguments. If you are interested in this, try checking out IntelliJ and this link for further instructions:

How do you input commandline argument in IntelliJ IDEA?


There is also another way which is using a jar file,

Passing on command line arguments to runnable JAR

Basically, a Jar file works on a terminal command line like this

java -jar (type_Something)

you can write a file path or a word.


- Explanations:

When you pass in a command line arguments, the first thing you pass in is for args[0].

Ex.

java -jar Hello

Hello gets stored in args[0], and then you can use it like this:

public class Test{
    public static void main(String[] args){
        String argument1 = args[0];
    }
}

But if you now add

java -jar Hello Friend

Hello is stored in args[0] and Friend in args[1]. Therefore, you can use it like this:

public class Test{
    public static void main(String[] args){
        String argument1 = args[0]; 
        String argument2 = args[1];
    }
}

- Personal Experience:

I have used the second method, using a jar, before. I believe I had to add a Jar in my IDE before using it on terminal inside my IDE (IntelliJ). I had to send a folder path to my program, and the only way allowed was using a jar to send in command line arguments.

Agent 0
  • 361
  • 1
  • 5
  • 17