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?

有帮助吗?

解决方案

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 &&)

其他提示

Another example with Apache Commons Lang:

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

javadoc

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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top