Session 2 |
Command-line arguments
Java main(String[] args)
method takes a string array named args as an argument. This is known as command-line arguments, which corresponds to the argments provided by the user when the java program is executed. For example, a Java program called HelloWorld can be invoked with additional command-line arguments as follows (in a "cmd" shell):
java HelloWorld Tartu Tallinn 180
Each element in the array args is a String (including "180"). If we need integers or doubles as an input, the conversion is needed:
int distance = Integer.parseInt(args[2]); double distance = Double.parseDouble(args[2]);
In the example, the first line converts the third element of array args (string "180") into an integer and the second line converts value into a double.
In IntelliJ, the command-line arguments can be input into the Program arguments (Run-menu - > Edit Configuration)
Session 2 |