First of all, you may want to use a command-line-arguments parsing facility.
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 Integer
s. 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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…