Reputation: 115
I have a command line with different parameters (strings and an int value).
The problem is that i have both spaces and = characters in this input string, which Java recognizes as separators.
Now i wonder how to parse this into my program.
I look for a possibility to make it as simple as possible. The parameter values must also be passed to various subroutines. So I'm looking for a way to easily access the parameters to pass them to subroutines and at the same time control that each command line contains these parameters (and that they actually contain valid value).
Maybe someone could give me a hint how to do this the most "correct" way.
Upvotes: 1
Views: 124
Reputation: 6123
Something like this:
public class Demo {
public static void main(String[] args) {
Map<String, String> cliParams = new HashMap<>();
// Full set of required parameters
cliParams.put("t", null);
cliParams.put("vo", null);
cliParams.put("q", null);
for (String arg : args) {
String[] nameAndValue = arg.split("=", 2);
if (nameAndValue.length != 2)
throw new IllegalArgumentException("Invalid parameter syntax: " + arg);
String name = nameAndValue[0];
String value = nameAndValue[1];
if (cliParams.replace(name, value) != null)
throw new IllegalArgumentException("Parameter given more than once: " + arg);
}
cliParams.forEach((k, v) -> {
if (v == null)
throw new IllegalStateException("Required parameter missing: " + k);
});
int q = Integer.parseInt(cliParams.get("q"));
}
}
Upvotes: 1