[Solved] Not able to execute a java program with arguments in console and eclipse? [duplicate]


You’re getting an ArrayIndexOutOfBoundsException because you’re accessing the command line arguments without checking that there actually are any.

You need to check whether the user provided the proper arguments, and if not, print a message how to call the executable as below

public class Assignment1 {
    public static void main(String args[]) {
        if (args.length == 2) {
            int c = Integer.parseInt(args[1]);
            if (c > args[0].length()) {
                System.out.println("the index " + args[1] + " is out of range !");
            } else {
                System.out.println("The character is " + args[0].charAt(c - 1) + " !");
            }
        }
        else {
            System.out.println("Usage: java Assignment1 <argument1> <argument2>\n E-g java Assignment1 abcd 4");
        }
    }
}

When debugging, you can pass command line arguments to your application like this:

In command line you have to run

javac Assignment1.java 

first. Then you have to execute

java Assignment1 <argument1> <argument2>

Or in Eclipse IDE, Open Run Configuration window and give two arguments in the Program Arguments box. Then Run it. This will work

enter image description here

3

solved Not able to execute a java program with arguments in console and eclipse? [duplicate]