java.lang.IllegalArgumentException : can't parse argument number MessageFormat

MessageFormat是在JAVA中經常用來定製消息的一個基礎類,用戶可以定義消息的模板,利用運行時的變量來填補模板中的佔位符(Place Holder),以達到靈活的輸出。但是如果新手不太注意很容易會碰到如上的錯誤信息,請看下面這段代碼:


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}。它會去解析括號中間的序號,在上述情況中括號間沒有數字,因此導致了不能解析的錯誤。

解決方法很簡單,就是類似字符串中的轉義字符,不同的是這裏用的是單引號('),代碼修改如下:

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));
    }
}

由於單引號也是特殊符號,這裏如果想要在輸出的信息中顯示單引號則需要打兩個單引號~


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章