Concept
How are command line arguments accessed and converted in Java?
ComputerScienceOne / The javamain() Method
"The number of arguments provided can be determined using the length property of the array. Specifically, args.length is an integer indicating how many arguments were provided. This does not include the name of the program (class) itself as that is already be known to the programmer. To access any one argument, it will be necessary to index the array. The index for the first argument is zero, thus the first argument is args[0] , the second is args[1] , etc. The last one would be at args[args.length-1] . If a user is expected to provide numbers as input, they’ll need to be converted as the args array are only String types. To convert the arguments you can use parsing methods provided by the Integer and Double classes. An example:\n\n1 //converts the \"first\" command line argument to an integer\n\n2 int x = Integer.parseInt(args[0]);\n\n3 //converts the \"third\" command line argument to a double:\n\n4 double y = Double.parseDouble(args[1]);"
Related Ideas
- What is the purpose of the main() method in a Java program?ComputerScienceOne · Comments
- How does the Java quadratic roots program check errors and calculate its roots?ComputerScienceOne · Quadratic Roots Revisited
- How are arrays of strings used in Java?ComputerScienceOne · Arrays of Strings
- How do argc and argv provide and convert command-line arguments?ComputerScienceOne · The cmain() Function
- How can conditionals verify the number of command line arguments?ComputerScienceOne · Life & Taxes
- How does a PHP script use entry points and command line arguments?ComputerScienceOne · Entry Point & Command Line Arguments
- How do you write a basic Hello World program in Java?ComputerScienceOne · Getting Started: Hello World
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units