Here’s a sample code in Java to handle command line parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.*; class Prompt { public static void main(String args[]) { if (args.length == 0) { System.out.println("No parameter."); return; } for (int i = 0; i < args.length; ++i) { System.out.print(i); System.out.print(" : "); System.out.println(args[i]); } } } |
You can get the number of arguments by args.length
.
And here are examples of execution. If you execute it without any parameter, it shows “No parameter”.
1 2 3 4 5 6 7 8 9 10 11 |
> javac Prompt.java > java Prompt No parameter. > java Prompt a b c 123 " "" 0 : a 1 : b 2 : c 3 : 123 4 : " |
Environment
I checked the above codes work in the following environment.
- OS: Windows 8
- JDK: 1.7.0_51