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
First of all, you may want to use a command-line-arguments parsing facility.
You're trying to access indices that do not exist:
You need to first check, then access:
There is also the case in which the arguments are not
Integer
s. You will get aNumberFormatException
if that's the case...Notes:
Short
if
notation (x ? y : z
) is used to returny
in casex
is true, otherwise it returnsz
.