user3505394
user3505394

Reputation: 315

Cleaner way to check number of arguments

I want to check the number of arguments passed by the user whether it is within the range of min and max values allowed. What will be the best way to achieve this?

What I have done so far:

 if(args.length < min || args.length > max)
      System.out.println("Invalid no. of args");

Can it be achieved using some open source libraries like Google Guava or Apache?

Upvotes: 0

Views: 96

Answers (3)

user3453226
user3453226

Reputation:

I suggest you to reverse your code. Use brackets and >= <= instead of > <.

if (args.length >= min && args.length <= max) {
    // Valid no. of args
} else {
    // Invalid no. of args
}

Upvotes: 0

Artur Malinowski
Artur Malinowski

Reputation: 1144

Another example with Apache Commons Lang:

if (!Range.between(min, max).contains(args.length)) {
    System.out.println("Invalid no. of args");
}

javadoc

Upvotes: 0

fge
fge

Reputation: 121712

Not sure if this is really cleaner but with Guava you can do this:

if (!Range.closed(min, max).contains(args.length))
    // blah blah

See the javadoc for Range

(what is more your initial code is wrong; you want ||, not &&)

Upvotes: 1

Related Questions