Skip to main content
MessageFormat
December 26, 2018

Code snippet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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, print no
  • 1# one → if 1, print one
  • 1< {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# → nothing
  • 1# → nothing
  • 1< → adds “s”

Example outputs:

args.lengthOutput
0You passed no argument
1You passed one argument
2You passed 2 arguments
5You passed 5 arguments