If a program relies on command line arguments as user input, like for example asking for an amount of shirts to order, a shirt size, and a color selection. I know these values would be stored in args[0]
, args[1]
, and args[2]
. But how would I manage cases in which one or more of those arguments isn't given by the user if I'm expecting to receive those values in that order. Like if the amount of shirts to order isn't given, is there a way that I can initialize that value to a default value of 1?
You get very little flexibility with command line arguments: the environment communicates them to you as a String[]
array, which implies that individual arguments have no names, only indexes.
You need to decide how to handle cases when one or more command-line arguments are missing, but keep in mind that it is not possible to "skip" arguments in the middle: whenever an argument is omitted, it is always the trailing argument. For example, if the user calls your program with parameters XXL GREEN
these would be placed in args[0]
and args[1]
, while args[2]
would be missing; the parameters would not be placed in args[1]
and args[2]
.
One simple choice is to treat situations when fewer than three arguments are specified as errors. If this is not flexible enough, you could parse parameters individually, and try to infer what they "mean". For example, if you see "S"
, "M"
, "L"
, "XL"
, or "XXL"
in any position, your program may take it as an indication of size.