Format a message

Source: Internet
Author: User

-- Start

Every program needs to display a message to the user, whether it is a successful message or a failed message. Generally, we construct a message through String concatenation. The following is a simple example.

Public static void main (string [] ARGs) throws exception {conflict in = new partition (system. In); system. Out. Print ("What is your name? "); String name = in. nextline (); system. Out. Print (" what's your birthday? "); Date Birthday = dateformat. getdateinstance (). parse (in. nextline (); int age = getage (birthday); // construct the message system by concatenating strings. out. println ("welcome" + name + ", your birthday is" + birthday + "and you are" + age + "years old. ");} public static int getage (date birthday) {calendar now = calendar. getinstance (); Calendar birthdaycal = calendar. getinstance (); birthdaycal. settime (birthday); return now. get (calendar. year)-birthdaycal. get (calendar. year );}

If we only target users in one country or region, the above practice is acceptable. however, there are many large companies that have offices in various countries and regions around the world. This requires us to display messages in different language environments. the methods provided by the messageformat class make it easy to construct messages. resourcebundle stores international messages. The following is a simple example.

public static void main(String[] args) throws Exception {displayMessage(Locale.CHINA);System.out.println();displayMessage(Locale.US);}private static void displayMessage(Locale currentLocale) throws Exception {ResourceBundle messages = ResourceBundle.getBundle("MessageBundle", currentLocale);Scanner in = new Scanner(;System.out.print(messages.getString("nameInfo"));String name = in.nextLine();System.out.print(messages.getString("birthdayInfo"));Date birthday = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale).parse(in.nextLine());int age = getAge(birthday);MessageFormat formatter = new MessageFormat("");formatter.setLocale(currentLocale);formatter.applyPattern(messages.getString("helloMsg"));System.out.println(formatter.format(new Object[] { name, birthday, age }));}private static int getAge(Date birthday) {Calendar now = Calendar.getInstance();Calendar birthdayCal = Calendar.getInstance();birthdayCal.setTime(birthday);return now.get(Calendar.YEAR) - birthdayCal.get(Calendar.YEAR);}

nameInfo = What is your name? birthdayInfo = What's your birthday? helloMsg = Welcome {0}, your birthday is {1,date,medium} and you are {2,number,integer} years old.

# What is your name? Nameinfo = \ u4f60 \ u53eb \ u4ec0 \ u4e48 \ u540d \ u5b57 \ u003f \ u0020 # What is your date of birth? Birthdayinfo = \ u4f60 \ u7684 \ u51fa \ u751f \ u5e74 \ u6708 \ u65e5 \ u662f \ u003f \ u0020 # Welcome to {0}. Your birthday is {1, date, date, medium}, you are {2, number, integer} years old. hellomsg = \ u6b22 \ u8fce \ u0020 \ u4f60 {0}, \ u4f60 \ u7684 \ u751f \ u65e5 \ u662f {1, date, medium }, \ u4f60 \ u4eca \ u5e74 {2, number, integer} \ u5c81 \ u4e86.

As we can see above, we need to convert the Chinese in resouce into unicode encoding. The following small program can help us do this, or you can use the Java installation directoryNative2asciiCommand to complete the same task.

Public static void main (string [] ARGs) throws exception {string S = "What is your name? "; For (char C: S. tochararray () {string codepoint = "0000" + integer. tohexstring (c); system. out. print ("\ U" + codepoint. substring (codepoint. length ()-4 ));}}

The running result of the preceding example is as follows:

What is your name? Shang Bo, what is your date of birth? Welcome to Shang Bo. Your birthday is 2000-1-1. You are 12 years old. What is your name? Scottwhat's your birthday? January 1, 2000 welcome Scott, your birthday is Jan 1, 2000 and you are 12 years old.

Usually we want to insert a date, time, String, number, currency, percentage, and other types of variables into the message. In the message, the variables to be inserted are in braces, which can be in the following form:

// FORM {argumentindex} {argumentindex, formattype} {argumentindex, formattype, formatstyle} // example welcome {0}, your birthday is {1, date, medium} And you are {2, number, integer} years old. formatter. format (new object [] {name, birthday, age}) // description argumentindex refers to the index in the array of object objects in the format method. formattype refers to the data type, which can be one of number, date, time, and choice. formatstyle refers to the formatting style, which can be short, medium, long, full, integer, currency, percent or custom format.

The following table summarizes the ing between formattype and formatstyle and format classes.

Format type Format Style Subformat created
(None) (None) Null
Number (None) Numberformat. getinstance (getlocale ())
  Integer Numberformat. getintegerinstance (getlocale ())
  Currency Numberformat. getcurrencyinstance (getlocale ())
  Percent Numberformat. getpercentinstance (getlocale ())
  Subformatpattern New decimalformat (subformatpattern, decimalformatsymbols. getinstance (getlocale ()))
Date (None) Dateformat. getdateinstance (dateformat. Default, getlocale ())
  Short Dateformat. getdateinstance (dateformat. Short, getlocale ())
  Medium Dateformat. getdateinstance (dateformat. Default, getlocale ())
  Long Dateformat. getdateinstance (dateformat. Long, getlocale ())
  Full Dateformat. getdateinstance (dateformat. Full, getlocale ())
  Subformatpattern New simpledateformat (subformatpattern, getlocale ())
Time (None) Dateformat. gettimeinstance (dateformat. Default, getlocale ())
  Short Dateformat. gettimeinstance (dateformat. Short, getlocale ())
  Medium Dateformat. gettimeinstance (dateformat. Default, getlocale ())
  Long Dateformat. gettimeinstance (dateformat. Long, getlocale ())
  Full Dateformat. gettimeinstance (dateformat. Full, getlocale ())
  Subformatpattern New simpledateformat (subformatpattern, getlocale ())
Choice Subformatpattern New choiceformat (subformatpattern)

Sometimes it looks very simple and difficult to construct a message. For example, I want to construct the following message.

There are n people

If n is 0, we cannot say "There are 0 people". We can only say "no one". English is more complex.

there is no poeple.there is one person.there are n poeple.

How to construct such a message? The choiceformat class can easily solve this problem.

Public static void main (string [] ARGs) throws exception {displaymessage (locale. china); system. out. println (); displaymessage (locale. US);} Private Static void displaymessage (locale currentlocale) throws exception {resourcebundle messages = resourcebundle. getbundle ("messagebundle", currentlocale); double [] limits = {0, 1, 2}; string [] formats = {messages. getstring ("no"), messages. getstring ("one"), messages. getstring ("more")}; choiceformat choiceform = new choiceformat (limits, formats); messageformat formatter = new messageformat (""); formatter. setlocale (currentlocale); formatter. applypattern (messages. getstring ("pattern"); formatter. setformats (new format [] {choiceform, numberformat. getinstance ()}); system. out. println (formatter. format (new object [] {0, 0}); system. out. println (formatter. format (new object [] {1, 1}); system. out. println (formatter. format (new object [] {2, 2}); system. out. println (formatter. format (new object [] {2, 3}); system. out. println (formatter. format (new object [] {2, 4}); system. out. println (formatter. format (new object [] {2, 5}); // 1. the first input parameter is 2 // 2. search for 2 in the limits array and find the subscript 2 in the array is 2 // 3. find the message whose subscript is 2 in the formats array, and the English environment is are {1} People // 4. replace {1} in the message with the second parameter 6 to obtain the are 6 lelesystem. out. println (formatter. format (new object [] {2, 6 }));}

# This pattern = \ u8fd9 {0 }. # No one = \ u6ca1 \ u6709 \ u4eba # one person one = \ u6709 \ u0031 \ u4e2a \ u4eba # {1} More = \ u6709 {1} \ u4e2a \ u4eba

pattern = there {0}.no = is no peopleone = is one personmore = are {1} people

The running result is as follows:

No one. this is one person. there are two people. there are 3 people. there are 4 people. five people. there are 6 people. there is no people. there is one person. there are 2 people. there are 3 people. there are 4 people. there are 5 people. there are 6 people.

---For more information, see:Java
--Shengming: reprinted, please indicate the source
-- Last updated on 2012-08-05
-- Written by shangbo on 2012-05-15
-- End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.