-->

JAVA Command line arguments to get info

2019-09-21 15:05发布

问题:

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

回答1:

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 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.