Java: pluralizer

Every now and then one needs to output quantities in plural and singular forms. In English language it is pretty much straightforward, just add an "s" to the end and you get a plural.

However, doing it programatically adds up a few lines of code that tend to make things less elegant (and simple) than they ought to be. For example, when listing the number of files inside a folder it is annoying to see a text saying "1 files", knowing that this is not grammatically correct.

To solve these cases, I've wrote a simple method.

    /**
     * This method simplifies showing values with associated terms when they
     * occur either in plural or singular manner. For example, solves the issue
     * of output "1 files" onto the correct "1 file"
     * @param value The value to output
     * @param text The text that will be "pluralized"
     * @return The pluralized text
     */
public static String pluralize(int value, String text){
   if(value == 1){
      return value + " " + text;
   }else{
    return value + " " + text + "s"; 
   }
}

As you can see, very simple code. From there I can rest assured that the correct form will be used according to the value that is used.

No comments:

Post a Comment