java 接收命令行参数,JAVA命令行参数获取信息

I just have a small question which i cant understand , i hope i can get some help please .

I Want to write a program that get the info into my program using the command line, example (java xx 10 20). In my program i got something like this

int coffeeCups= Integer.parseInt(args[0]);

int coffeeShots= Integer.parseInt(args[1]);

if (args.length==0)

{

System.out.print ("No arguments..");

System.exit(0);

}

else if (args.length==1)

{System.out.println("not enough arg..");

System.exit(0);

}

else if (args.length>2)

{System.out.println("too many arg.");

System.exit(0);

}

else if (Integer.parseInt(args[0]<0) && Integer.oarseInt(args[1]<0)

{system.out.println("negative chain arg");

System.exit(0); }

else if (Integer.parseInt(args[0]<0) || Integer.oarseInt(args[1]<0)

{system.out.println("negative arg");

System.exit(0);}

I Want to enter only TWO POSITIVE INTEGERS INTO MY COMMAND LINE.. otherwise it should reject my inputs, but the thing is that sometime i came with en error like that (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0) and sometimes my program runs without even entering any two integers in the COMMAND LINE...

I gotta finish my code as soon as possible, and i'de appreciate ur help

P.S. dont worry about the my identation as my program is not done yet

解决方案

You're trying to access indices that do not exist:

// who said there is a first argument?

int coffeeCups = Integer.parseInt(args[0]);

// who said there is a second argument?

int coffeeShots = Integer.parseInt(args[1]);

You need to first check, then access:

// this is just like using sentinel value. If you're not familiar with

// shortend `if` see notes.

int coffeeCups = args.length > 1 ? Integer.parseInt(args[0]) : null;

int coffeeShots = args.length > 2 ? Integer.parseInt(args[1]) : null;

if (coffeeCups == null || coffeeShots == null){

throw new Exception("Not enough arguments");

}

if (args.length > 2){

throw new Exception("Too many arguments");

}

There is also the case in which the arguments are not Integers. You will get a NumberFormatException if that's the case...

Notes:

Short if notation (x ? y : z) is used to return y in case x is true, otherwise it returns z.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值