0

I'm working on a program public class Talk that connects client and server in two way communication. I will be running the program using a Terminal window. How do I add command line options so that these work Talk –h [hostname | IPaddress] [–p portnumber], or Talk –s [–p portnumber], or Talk –a [hostname|IPaddress] [–p portnumber], or Talk –help

This is what I have so far:

if (args[0] == "-h" && args[2] == "-p" && (Integer.parseInt(args[3]) % 1 == 0)) {

            // code for Talk –h [hostname | IPaddress] [–p portnumber]

        } else if (args[0] == "-s" && args[1] == "-p" && (Integer.parseInt(args[2]) % 1 == 0)) {

            // code for Talk –s [–p portnumber]

        } else if (args[0] == "-a" && args[2] == "-p" && (Integer.parseInt(args[3]) % 1 == 0)) {

            // code for Talk –a [hostname|IPaddress] [–p portnumber]

        } else if (args[0] == "-help") {

            // code for Talk –help

        } else {

            System.out.println("Invalid invocation, use -help for instructions on how to use program");
            System.exit(-1);

        }

Is this the correct way to add command-line options? and their constraints?

Hamza
  • 11
  • 4
  • Looks OK. You don't need the parentheses around `Integer.parseInt(args[3]) % 1 == 0`. – user207421 Sep 29 '20 at 03:59
  • [That's not how to compare Strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) and _all_ values returned by `parseInt` satisfy `%1==0` but most of them aren't valid port numbers (at least for TCP and UDP, you didn't say). Also, `[]` in a usage message usually means _optional_ i.e. may be omitted but you aren't allowing that. Also, negative process exit codes usually don't work. – dave_thompson_085 Sep 29 '20 at 06:42

1 Answers1

0

Unless it's an educational exercise, you might do better with one of the well-established libraries for parsing the command line. common-cli (https://commons.apache.org/proper/commons-cli/) is one such, although there are others.

The problem is that parsing command-line options robustly is hard. There are all sorts of complexities to deal with, and the error-checking alone can be quite burdensome.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15