MessageFormat
Pluralizing messages with Java MessageFormat and ChoiceFormat, with example outputs.
1 min read
Code snippet
import java.text.MessageFormat;import java.util.logging.Logger;import static java.util.logging.Level.INFO;
public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) { String pattern = "You passed{0,choice,0# no |1# one |1< {0} }argument{0,choice,0#|1<s}"; String message = MessageFormat.format(pattern, args.length); logger.log(INFO, message); }}Understanding the code snippet
{0,choice,0# no |1# one |1< {0} }: This part is a ChoiceFormat that behaves based on the value of {0} (i.e., the number of arguments):
0# no→ if 0, printno1# one→ if 1, printone1< {0}→ if more than 1, print the actual number (e.g., 2, 3, etc.)
argument{0,choice,0#|1<s}: This part formats the word argument to add “s” only if {0} is not 0 or 1 (i.e., plural form).
0#→ nothing1#→ nothing1<→ adds “s”
Example outputs:
args.length |
Output |
|---|---|
| 0 | You passed no argument |
| 1 | You passed one argument |
| 2 | You passed 2 arguments |
| 5 | You passed 5 arguments |