English 中文(简体)
Java的NumberFormat的奇怪行为
原标题:Strange behaviour of NumberFormat Java

我有以下法典,以划分一个叫做“体”的“强食变量”。

NumberFormat formatter = NumberFormat.getInstance();
Number number = formatter.parse(str);

我希望在str不是数字时捕获抛出的异常以进行验证。我遇到的问题是它并不总是抛出预期的ParseException。当字符串str以数字开头但后面是字符时,似乎会获取字符串的前几个字符并将它们解析为数字。

例如:

  • if str="a10" then is thrown a ParseException
  • if str="10a" then no exception thrown and number=10

我不能使用双管齐下,因为镜头可以有1 000.98等 com体和点子,而这种格式不为这种方法所理解。

Why is this happening? Can I validate it in any other way? Thanks

最佳回答

这种行为并不奇怪,这是按设计实现的。

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

2. 您可采用诸如以下等提高职位认识的方法:

public static double parse(String str) throws ParseException {
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition position = new ParsePosition(0);
  Number number = formatter.parse(str, position);
  if (position.getIndex() != str.length()) {
    throw new ParseException("failed to parse entire string: " + str, position.getIndex());
  }
  return number.doubleValue();
} 
问题回答

如果您查看API,它明确指出:

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.

如果你想查看解析器解析了多远,你可以使用其他位置感知方法。这样你就可以检查是否有任何尾随字符。你也可以使用比如通用语言isAlpha检查整个字符串是否包含字母数字字符。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签