Java:检查命令行参数

时间:2013-09-23 15:04:32

标签: java

我知道很容易我可以使用try / catch来检查命令行参数是否为。

我正在寻找一种方法来检查这一点,而无需使用昂贵的try / catch块。我对Java很新。我在几个论坛上搜索过,但没有找到任何与我的问题有关的内容。

System.out.println(Double.parseDouble(args[1]));

^^这会导致错误。除了把它放在一个try / catch中,有人会指向我进行数据验证,这会阻止这个吗?假设args [1]是一串文本。

4 个答案:

答案 0 :(得分:5)

try - catch方法是普遍接受的方法,主要是因为实际上有效的双重格式可以有很多格式:

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;

所有这些都是有效的双打,可以通过parseDouble()从字符串中解析。 Double.parseDouble("NaN")Double.parseDouble("Infinity")也有效(尽管NaNInfinity不是文字)。更不用说parseDouble()也处理前导或尾随空格。所以我的答案是:不要!使用try - catch方法。 可以构造一个匹配某些子集(或者甚至可能是所有)有效双精度格式的正则表达式,但我怀疑它实际上比捕获和处理NumberFormatException更有效。< / p>


valueOf()的文档中实际解释了完整的正则表达式:

  

为避免在无效字符串上调用此方法并抛出NumberFormatException,可以使用下面的正则表达式来筛选输入字符串:

  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
  }

正如你所看到的,它有点像一个讨厌的正则表达式。

答案 1 :(得分:1)

作为评论者ÓscarLópez说,只需使用try / catch块并捕获NumberFormatException。这是确保目标字符串是格式正确的双精度的正确方法,并且try / catch构造的潜在开销值得程序的正确性和清晰度。

Double d = null;
try {
  d = Double.parseDouble(args[1]);
} catch (NumberFormatException nfe) {
  // TODO
}

答案 2 :(得分:1)

Java没有开箱即用的isDoubleisNumeric方法,但您可以自己编写它们:

public static boolean isDouble(String s) {
    try {
        Double.parseDouble(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

但是double有许多方法可以写出来:

  • 23.2
  • 23F
  • 23e10
  • 2_3.4_5(无法使用Double#parseDouble(String)解析)
  • 2_3E1_0d(无法使用Double#parseDouble(String)解析)

如果您只是想检查XX.XXX模式,这是使用RegEx的方法:

public static boolean isDoubleDigits(String s) {
    return s.matches("\\d+(\\.\\d{1,2})?");
}

答案 3 :(得分:0)

为什么不使用框架进行命令行输入验证?结帐Apache Commons CLI project