For example, the user run my programme like this
myprogram -p1 my_name, -p2 my_address, -p3 my_gender
But the user may type this, and it still valid:
myprogram -p2 my_address, -p1 my_name,-p3 my_gender
How can I parse it in Java? Thanks.
For example, the user run my programme like this
myprogram -p1 my_name, -p2 my_address, -p3 my_gender
But the user may type this, and it still valid:
myprogram -p2 my_address, -p1 my_name,-p3 my_gender
How can I parse it in Java? Thanks.
You can use something like this:
public static void main (String[] args) {
for(int i = 0; i < args.length; i++) {
if(args[i].equals("-p1")) {
// args[i+1] contains p1 argument
} else if(args[i].equals("-p2")) {
// args[i+1] contains p2 argument
}
}
}
Make sure to check whether the i+1 argument is there, otherwise an exception will be thrown.
There are more advanced methods of going this, you could e.g. use hashing to map the flag to the processing function. But, for this purpose, I guess this will do.
What I do not understand is the use of comma's in your sample. What are they used for?
If you're looking for a DIY, then maybe this might be starting point.
public class Foo
{
private static final String[] acceptedArgs = { "-p1", "-p2", "-p3" };
public void handleCommandArgs(String... args)
{
if (args != null)
{
for (int argIndex = 0; argIndex < args.length; argIndex++)
{
for (int acceptedIndex = 0; acceptedIndex < acceptedArgs.length; acceptedIndex++)
{
if (args[argIndex] != null && args[argIndex].equals(acceptedArgs[acceptedIndex]))
{
String arg = args[argIndex], param = args[argIndex + 1];
performRoutine(arg, param);
}
}
}
}
}
private void performRoutine(String arg, String param)
{
System.out.println(arg + " ->" + param.replace(",", ""));
}
public static void main(String[] args)
{
(new Foo()).handleCommandArgs(args);
}
}
Sample from Java Tutorials @Oracle
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
The params come in a vector of String.