我知道我可以很容易地使用 try/catch 来检查命令行参数是否为 double 值。
我正在寻找一种无需使用代价高昂的 try/catch block 即可进行检查的方法。我是 Java 的新手。我搜索了几个论坛,但没有找到任何与我的问题相关的内容。
System.out.println(Double.parseDouble(args[1]));
^^这会导致错误。除了将其放入 try/catch 之外,有人可以指出我可以防止这种情况发生的数据验证吗?假设 args[1] 是一串文本。
最佳答案
try
-catch
方法是执行此操作的普遍接受的方法,主要是因为实际上有效的 double 可以有很多格式:
double a = 42.e10; // or 42.E10
double b = 42.f; // or 42.F
double c = 42.d; // or 42.D
double d = 010E010D;
double e = 0x1.fffffffffffffP+1023;
double f = 0x1.0p-1022;
所有这些都是有效的 double 值,可以通过 parseDouble()
从字符串中解析出来。 Double.parseDouble("NaN")
和 Double.parseDouble("Infinity")
也是有效的(尽管 NaN
和 Infinity
不是文字)。更不用说 parseDouble()
还处理前导或尾随空格。所以我的回答是:不要!使用 try
-catch
方法。 有可能构造一个正则表达式来匹配某些(或什至所有)有效 double 格式的子集,但我怀疑这实际上会比捕获和处理 NumberFormatException
.
valueOf()
的文档中实际上解释了完整的正则表达式:
To avoid calling this method on an invalid string and having a
NumberFormatException
be thrown, the regular expression below can be used to screen the input string:final String Digits = "(\\p{Digit}+)"; final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. final String Exp = "[eE][+-]?"+Digits; final String fpRegex = ("[\\x00-\\x20]*"+ // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from section 3.10.2 of // The Java™ Language Specification. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.("+Digits+")("+Exp+")?)|"+ // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional trailing "whitespace" if (Pattern.matches(fpRegex, myString)) Double.valueOf(myString); // Will not throw NumberFormatException else { // Perform suitable alternative action }
如您所见,它是一个有点讨厌的正则表达式。
关于Java:检查命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962673/