0

在 Java 中,该类java.util.Scanner提供了一种方便的方法来解析长字符串。在我的特殊情况下,我必须解析具有许多double值的字符串,为此我使用该nextDouble()方法。

有时,我的输入字符串包含nan而不是有效的浮点数。不幸的是,Scanner似乎只识别NaN非数字。

有没有办法教它也认nanLocale也许通过设置自定义DecimalFormatSymbols.setNaN()

4

2 回答 2

1

One option is setting a custom Locale. Another option is that internally the scanner uses a regular expression to retrieve a double-string and then uses Double.parseDouble to convert it to a double, so you could call Scanner#next(Pattern pattern) using the regular expression defined here except using "nan" instead of "NaN" and then call Double.parseDouble on the returned string.

于 2013-04-14T19:49:32.707 回答
1

这样的事情怎么样?

private static final Pattern nan =
        Pattern.compile("nan", Pattern.CASE_INSENSITIVE);
public static boolean hasNextDouble(Scanner scanner) {
    if(scanner == null)
        return false;
    return scanner.hasNext(nan) || scanner.hasNextDouble();
}
public static double nextDouble(Scanner scanner) {
    if(scanner.hasNext(nan)) {
        scanner.next();
        return Double.NaN;
    }
    return scanner.nextDouble();
}
于 2013-04-14T19:50:59.777 回答