0

I am solving a question where the requirement is that the program should allow the user to set a parameter with the -d command-line option. Does java provide any mechanism to pass argument with -d option? I couldn't find any so I am interpreting this as if the command line option value is -d, that means that user wants to enter the parameter next.

if ( args[0].equals("-d") )
{
     parameter = args[0];
}

Is this right way to check that? Is there some better way to check whether user has entered -d option? Does java provides some other mechanism for that?

Vraj
  • 95
  • 1
  • 8
  • Use a command line argument parser. [JCommander](http://jcommander.org/) (no affiliation) is my preference - there are others. – Boris the Spider Jul 30 '16 at 08:40
  • Then `parameter = "-d"`, or `null` - is that what you want? Have a look at Apache Commons CLI for example; and http://stackoverflow.com/questions/10745811/how-to-use-terminal-arguments-with-values-in-java – Has QUIT--Anony-Mousse Jul 30 '16 at 08:51

3 Answers3

2

I think the requirement means -D (the capital one), not -d. Such options are used to pass additional parameters to java. For instance, -Dmy.option=value. In such case you have access to this property by means of System class:

String myOption = System.getProperty("my.option");
Andrew Lygin
  • 6,077
  • 1
  • 32
  • 37
1

What if someone runs the program with ./yourapp something else -d? Now the argument -d exists, but not on position 0

So, my recommendation is to loop through all of the arguments and check what you need.

int i;
boolean dParam = false;
for (i = 0; i < args.length; i++) {
    if (args[i].equals("-d")) {
        dParam = true;
    }
}

If you want the user to input something after the -d, like a filename then I would recommend doing this:

int i;
boolean dParam = false;
String dParamValue;

for (i = 0; i < args.length; i++) {
    if (args[i].equals("-d")) {
        dParam = true;
        dParamValue = args[++i];
    }
}
Ibrahim
  • 2,034
  • 15
  • 22
0

All parameters you pass to the program you are running, are going in the application throug the parameter String[] args in the main method..

You can then check if the dictionary is there requested, by just checking if the array of arguments contains that key..

Example:

public static void main(String[] args) {
System.out.println("is dictionary there?: " + Arrays.asList(args).contains("d"));

if (Arrays.asList(args).contains("d")) {
    prepateDictionary();
}else {
    prepareSomethingElse();
}

}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97