Java 为什么DecimalFormat允许字符作为后缀?
我正在使用Java 为什么DecimalFormat允许字符作为后缀?,java,formatting,Java,Formatting,我正在使用DecimalFormat解析/验证用户输入。不幸的是,它允许在解析时将字符作为后缀 示例代码: try { final NumberFormat numberFormat = new DecimalFormat(); System.out.println(numberFormat.parse("12abc")); System.out.println(numberFormat.parse("abc12")); } catch (final ParseException e
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”
?:
从给定字符串的开头解析文本以生成数字该方法不能使用给定字符串的整个文本。
下面是一个示例,它可以让您了解如何确保考虑整个字符串
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
使用方法的parse(String,ParsePosition)
重载,在解析后检查ParsePosition的.getIndex(),查看它是否与输入的长度匹配