cmdlineparser java_Apache command line parser

I got the code below from a sample code from tutorials point and tweaked it a little bit.

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;

}

}

Now, my question is that, when i try to execute the above code with a parameter of -multi it will still be accepted? I've already set the options to receive only either -m or -multiply. However, it will still accept -multi

I am using commons-cli-1.3.1 (im trying to debug a legacy code by the way)

Note: Above source is a SAMPLE source only, no need to apply actual coding guidelines (good or bad) i just want to know why the behavior happens as it is.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值