문제

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