- Before using command-line arguments, always check the number of arguments before accessing the array elements so that there will be no exception generated.
- For example, if your program needs the user to input 6 arguments,
Method 1:
if( args.length != 6 ){ System.out.println("Invalid number of arguments"); System.out.println("Please enter 6 arguments"); } else{ //Code to process the arguments }
or,
Method 2:
if( args.length > 0 ){ //Do some processing using the arguments } else{ System.out.println("Invalid number of arguments"); }