【问题标题】:Why does DecimalFormat allow characters as suffix?为什么 DecimalFormat 允许字符作为后缀?
【发布时间】:2017-11-15 23:02:11
【问题描述】:

我正在使用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" 这样的输入?

【问题讨论】:

    标签: java formatting


    【解决方案1】:

    来自NumberFormat.parse的文档:

    从给定字符串的开头解析文本以生成一个数字。 该方法可能不会使用给定字符串的整个文本。

    这是一个示例,应该让您了解如何确保考虑整个字符串。

    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
    

    【讨论】:

      【解决方案2】:

      使用方法的parse(String, ParsePosition)重载,解析后检查ParsePosition的.getIndex(),看是否匹配输入的长度。

      【讨论】:

        猜你喜欢
        • 2014-12-03
        • 1970-01-01
        • 2012-03-07
        • 2019-11-29
        • 1970-01-01
        • 2013-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多