Dimitrios Sria Dimitrios Sria - 2 months ago 8
Java Question

How to use main args[] to call functions

I am wondering if there is any way of calling a class function by using main args[] instead of having like the following:

public class Test {

public static void main(String[] args) {

String choice="";
System.in(choice);

if (choice.contains("1"))
{
Item item = new Item();
item.function();
}
else
{
Item2 item2 = new Item2();
item2.function2();
}


}

}


And have something like:

-a calls the x function
-b calls the y function

Answer

In a main method args is an array containing the passed arguments to your program, so you can access its elements by index like any other Java array.

This is what you need to do:

if (args[0].contains("a")){
    Item item = new Item();
    item.function();
}
else if(args[0].contains("b")){
    Item2 item2 = new Item2();
    item2.function2();
}