我从教程点下面的代码示例代码和调整它一点点。
App.java
public static void main(String[] args) throws ParseException {
CommandTest t = new CommandTest();
t.start(args);
}
CommandTest.java
public class CommandTest {
void start(String[] args) throws ParseException {
//***Definition Stage***
// create Options object
Options options = new Options();
// add option "-a"
options.addOption(
Option.builder("a")
.longOpt("add")
.desc("add numbers")
.hasArg(false)
.valueSeparator('=')
.required(false)
.build()
);
// add option "-m"
options.addOption("m", false, "");
options.addOption(
Option.builder("m")
.longOpt("multiply")
.desc("multiply numbers")
.hasArg(false)
.valueSeparator('=')
.required(false)
.build()
);
//***Parsing Stage***
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
//***Interrogation Stage***
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
System.out.println("Sum of the numbers: " + getSum(args));
} else if(cmd.hasOption("m")) {
System.out.println("Multiplication of the numbers: " + getMultiplication(args));
}
}
public static int getSum(String[] args) {
int sum = 0;
for(int i = 1; i < args.length ; i++) {
sum += Integer.parseInt(args[i]);
}
return sum;
}
public static int getMultiplication(String[] args) {
int multiplication = 1;
for(int i = 1; i < args.length ; i++) {
multiplication *= Integer.parseInt(args[i]);
}
return multiplication;
}
}
现在,我的问题是,当我试着使用的参数来执行上面的代码-multi
还是会被接受? 我已经设置的选项只接收或者-m
或-multiply
。 但是,它仍然会接受-multi
我使用的commons-CLI-1.3.1(我尝试的方式来调试遗留代码)
注:以上源是样品来源而已,无需申请实际编码指南(好或坏)我只是想知道为什么会发生的行为,因为它是。