The brief ive been given is to write a Java prg to take some command line arguements of the form
JavaProg -n[anInt] -o[inputFileName] -o[outputFileName] -s[aStringWord]
and then use them.

Now I understand very basic args[] use. But in the brief there may be missing args and placed out of order. I am not familiar with the -n, -o -s sintax as not Unix/Command window user. Apparently there is a way of doing this.

as I cant just do int num = Integer.parseInt(args[0]); as may not be first.

any ideas?

Well, all the args come as String first and they will (or should) all start with "-". So, chop the first character of the String (if it is not "-" then return an error and exit). Then chop the next character (charAt()) and run that through a switch statement.

i.e.

int n;
File i;
for (String arg : args) {
  if (arg.charAt(0) != '-') {
    System.err.println("whatever");
    System.exit(1);
  }
  switch (arg.charAt(1)) {
    case 'n':
      n = Integer.parseInt(arg.substring(2));
      break;
    case 'i':
      i = new File(arg.substring(2));
      break;
    default:
      System.err.println("Invalid .....");
      System.exit(1);
      break;
  }
}

I think there's a library in the Jakarta Commons project that's supposed to pretty much automate commandline parameter parsing.
Whether it's easier to use that than parse them yourself I can't tell as I've not used it ;)

I think there's a library in the Jakarta Commons project that's supposed to pretty much automate commandline parameter parsing.
Whether it's easier to use that than parse them yourself I can't tell as I've not used it ;)

I should have known, but then again I don't deal with this too often either, so I haven't bothered looking for an API. But, if its a "common" task, jakarta commons usually has something for it. ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.