(Appendix) Command-line Arguments
Table of Contents
Introduction
Oftentimes you'll want to write programs that take input directly from the user. One way to accomplish that is to take in arguments from the command line—i.e. directly from the terminal itself. It's actually rather simple to do so.
Taking Command-line Arguments
The Java Programming Language Specification does not precisely lay out how command line arguments are to be had. It does, however, suggest how they tend to be processed through the use of the main method's String[] parameter (ยง 12.1).:
public static void main(String[] args){}
For example, if I want to write a program called Hello.java which will say "Hello" to every name given in the command line, I could write the following:
1: public class Hello{ 2: public static void main(String[] args){ // args is a conventional name, but is not required 3: for(String name : args){ 4: System.out.printf("Hello, %s!\n", name); 5: } 6: } 7: }
Then I can compile and run it with three arguments:
josephraskind@stargazer:/tmp/CLI$ javac Hello.java; java Hello Marx Engels Lenin Hello, Marx! Hello, Engels! Hello, Lenin!
Converting Command-line Arguments
Command line arguments are always Strings. This means you must convert them if you want to take in numbers to perform calculations. For example, if I want to write a program that calculates standard deviation:
1: public class Statistics{ 2: public static void main(String[] args){ 3: int size = args.length; 4: double[] elements = new double[size]; 5: double sum = 0; 6: 7: for(int i = 0; i < size; i++){ 8: elements[i] = Double.parseDouble(args[i]); 9: sum += elements[i]; 10: } 11: 12: double mean = sum / size; 13: sum = 0; 14: 15: for(int i = 0; i < size; i++){ 16: sum += Math.pow(elements[i] - mean, 2); 17: } 18: 19: double std = Math.sqrt(sum / size); 20: System.out.printf("mean: %.2f%n std: %.2f%n", mean, std); 21: } 22: }
josephraskind@stargazer:/tmp/CLI$ javac Statistics.java; java Statistics 1 2 3 mean: 2.00 std: 0.82
Common functions for String conversions are listed below for reference:
Integer.parseInt(str)- String to int
Long.parseLong(str)- String to long
Double.parseDouble(str)- String to double