Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top