MessageFormat是在JAVA中常常用來定製消息的一個基礎類,用戶能夠定義消息的模板,利用運行時的變量來填補模板中的佔位符(Place Holder),以達到靈活的輸出。可是若是新手不太注意很容易會碰到如上的錯誤信息,請看下面這段代碼:java
import java.text.MessageFormat; public class TestMessageFormat { public static void main(String[] args) { System.out.println(MessageFormat.format("The username cannot contain any of these characters: (){}",null)); } }
這段小程序僅僅用來輸出提醒用戶用戶名不能包含(){}這四個符號,可是就會出現如上的錯誤。究其緣由就在於那對中括號,在MessageFormat中它是用來表示佔位符的,如{0},{1}。它會去解析括號中間的序號,在上述狀況中括號間沒有數字,所以致使了不能解析的錯誤。
小程序
解決方法很簡單,就是相似字符串中的轉義字符,不一樣的是這裏用的是單引號('),代碼修改以下:ide
import java.text.MessageFormat; public class TestMessageFormat { public static void main(String[] args) { System.out.println(MessageFormat.format("The username cannot contain any of these characters: ()'{'}", null)); } }
因爲單引號也是特殊符號,這裏若是想要在輸出的信息中顯示單引號則須要打兩個單引號~
orm