I am programming a morse code translator in Kotlin, for the input I use the arguments of the main method:
fun main(args: Array<String>)
I use org.apache.commons.cli to manage the command options (-d to decode and -e to encode). The thing is that when entering morse code the program confuses it with command options (because it uses dashes).
Example of use of the program:
morse-translator -d --. .- .
Returns:
Exception in thread "main" org.apache.commons.cli.UnrecognizedOptionException: Unrecognized option: --.
I enclose the class that handles the command options:
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.Options
class Input(args: Array<String>) {
private var flags: Options = Options()
private var parser: DefaultParser = DefaultParser()
private var cli: CommandLine
init {
setupOptions()
cli = parser.parse(flags, args)
}
/** Determine the flags allowed */
private fun setupOptions() {
flags.addOption("e", "encode", false, "Encode message")
flags.addOption("d", "decode", false, "Decode message")
}
}
I tried surrounding the morse code with double quotation marks, but same problem.
Commons-cli observes the default solution on Unix to specify "--" to instruct the commandline parser that no more options should be parsed.
The following Java snippet include "--" in the list of arguments, then it properly parses the string as a trailing argument:
Options options = new Options();
options.addOption("d", "decode", false, "Decode message");
options.addOption("e", "encode", false, "Encode message");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, new String[] {"-d", "--", "--. .- ."});
assertTrue(cmd.hasOption("d"));
assertFalse(cmd.hasOption("e"));
assertEquals("[--. .- .]", cmd.getArgList().toString());
assertEquals("[--. .- .]", Arrays.toString(cmd.getArgs()));