java – 為什麼DecimalFormat允許字元作為字尾?
我使用DecimalFormat來解析/驗證使用者輸入.不幸的是,它在解析時允許字元作為字尾.
示例程式碼:
try { final NumberFormat numberFormat = new DecimalFormat(); System.out.println(numberFormat.parse("12abc")); System.out.println(numberFormat.parse("abc12")); } catch (final ParseException e) { System.out.println("parse exception"); }
結果:
12 parse exception
我實際上會期待兩者的解析異常.如何告訴DecimalFormat不允許輸入像“12abc”?
NumberFormat.parse
的文件:
Parses text from the beginning of the given string to produce a number.The method may not use the entire text of the given string.
這是an example ,應該給你一個想法如何確保整個字串被考慮.
import java.text.*; public class Test { public static void main(String[] args) { System.out.println(parseCompleteString("12")); System.out.println(parseCompleteString("12abc")); System.out.println(parseCompleteString("abc12")); } public static Number parseCompleteString(String input) { ParsePosition pp = new ParsePosition(0); NumberFormat numberFormat = new DecimalFormat(); Number result = numberFormat.parse(input, pp); return pp.getIndex() == input.length() ? result : null; } }
輸出:
12 null null
http://stackoverflow.com/questions/4324997/why-does-decimalformat-allow-characters-as-suffix