public class CmdLineProgram { /* * Precondition: * The program knows the minimum and maximum number of arguments * which he allows */ public static void main(String[] args) { int minNrOfArgs = 0; //Minimum number of arguments int maxNrOfArgs = 2; //Maximum number of arguments try { if(args.length >= minNrOfArgs && args.length <=maxNrOfArgs) { if(args.length!=0) { System.out.println("The arguments are: "); for(String s: args) System.out.println(s); } System.out.println("Total number of arguments: " + args.length); } else { if(args.length <= minNrOfArgs) throw new Exception("Number of arguments is " + args.length + ".\n" + "At least " + minNrOfArgs + " are required."); else throw new Exception("Number of arguments is " + args.length + ".\n" +"At most " + minNrOfArgs + " are permitted."); } } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } } }What the program does:
Knowing the minimum and maximum number of arguments, the program checks if the length of the argument String vector (args) is between those values. If that is true, it will output the number of arguments and the value of each argument using a foreach loop (still, he will not output the arguments if he didn't receive any and will only show 0).
If the number of arguments is not correct (too many of too few) it will throw an exception and output that exception.
No comments:
Post a Comment
Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!