【问题标题】:How to check Type before casting in java如何在Java中进行类型转换之前检查类型
【发布时间】:2012-11-14 19:29:58
【问题描述】:

我将我的字符串变量转换为整数和双精度。我想在运行时检查 String 变量是否包含有效的 Integer 或 Double 值。

我遵循代码,但它对我不起作用。

String var1="5.5";
String var2="6";
Object o1=var1;
Object o2=var2;
if (o1 instanceof Integer)
{
    qt += Integer.parseInt( var1);// Qty
}
if (o2 instanceof Double)
{
    wt += Double.parseDouble(var2);// Wt
}

【问题讨论】:

  • o1 和 o2 绝对不是 Integer 的实例,因为它们都引用了 String 对象
  • 您将 String 向上转换为 Object,因此 o1 instanceOf Integer 永远不会为真。

标签: java casting type-conversion typechecking


【解决方案1】:

尝试解析int,如果失败则捕获异常:

String var1="5.5";

try {
 qt += Integer.parseInt( var1);
}    
catch (NumberFormatException nfe) {
// wasn't an int
}

【讨论】:

  • 我知道这种技术,但我想避免发生异常
  • @SyedMuhammadMubashir.. 这就是我们所说的避免异常发生。我们应该处理它们。并且是否引发异常,完全取决于您要转换的字符串。当然你不能转换""
  • 你可能想看看stackoverflow.com/questions/9619603/no-tryparsedouble-in-java,或者一个重复的问题。
【解决方案2】:

您可以使用模式来检测字符串是否为整数:

  Pattern pattern = Pattern.compile("^[-+]?\\d+(\\.\\d+)?$");
  Matcher matcher = pattern.matcher(var1);
  if (matcher.find()){
      // Your string is a number  
  } else {
      // Your string is not a number
  }

您必须找到正确的模式(我已经有一段时间没有使用它们了)或者有人可以用正确的模式编辑我的答案。

*EDIT**:为您找到了一个模式。编辑了代码。我没有对其进行测试,但它取自 java2s 站点,该站点还提供了一种更优雅的方法(从该站点复制):

 public static boolean isNumeric(String string) {
      return string.matches("^[-+]?\\d+(\\.\\d+)?$");
  }

【讨论】:

  • 如果是String.matches,则不需要使用anchors。这是隐含的。
  • 你去 - +1 老实说,你复制的。 :)
【解决方案3】:

首先,您的if 条件肯定会失败,因为object 引用实际上指向一个String 对象。因此,它们不是任何integerdouble 的实例。

要检查字符串是否可以转换为integerdouble,您可以按照@Bedwyr 的答案中的方法,或者如果您不想使用try-catch,正如我从您的cmets 中假设的那样那里(其实我不明白你为什么不想用它们),你可以用一点pattern matching:-

String str = "6.6";
String str2 = "6";

// If only digits are there, then it is integer
if (str2.matches("[+-]?\\d+")) {  
    int val = Integer.parseInt(str2);
    qt += val;
}

// digits followed by a `.` followed by digits
if (str.matches("[+-]?\\d+\\.\\d+")) {  
    double val = Double.parseDouble(str);
    wt += val;
}

但是,请理解,Integer.parseIntDouble.parseDouble 是执行此操作的正确方法。这只是一种替代方法。

【讨论】:

    【解决方案4】:

    也许正则表达式可以满足您的需求:

    public static boolean isInteger(String s) {
        return s.matches("[-+]?[0-9]+");
    }
    
    public static boolean isDouble(String s) {
        return s.matches("[-+]?([0-9]+\\.([0-9]+)?|\\.[0-9]+)");
    }
    
    public static void main(String[] args) throws Exception {
        String s1 = "5.5";
        String s2 = "6";
        System.out.println(isInteger(s1));
        System.out.println(isDouble(s1));
        System.out.println(isInteger(s2));
        System.out.println(isDouble(s2));
    }
    

    打印:

    false
    true
    true
    false
    

    【讨论】:

    • @SyedMuhammadMubashir 你在卖名誉吗?!我不会赞成你的问题,但你可以不赞成我的问题;)
    • @SyedMuhammadMubashir .. 我假设您在 SO 上提问,是为了学习一些东西,而不是为了购买声誉。如果您这样做是为了以后,那么宁愿在这里回答问题。并给出很好的答案,如果你知道的话。不要在这里敦促人们为您的帖子投票。
    【解决方案5】:

    Integer.parseIntDouble.parseDouble 返回String 的整数/双精度值。如果String 不是有效数字,该方法将抛出NumberFormatException

    String var1 = "5.5";
    
    try {
        int number = Integer.parseInt(var1); // Will fail, var1 has wrong format
        qt += number;
    } catch (NumberFormatException e) {
        // Do your thing if the check fails
    }
    
    try {
        double number = Double.parseDouble(var1); // Will succeed
        wt += number;
    } catch (NumberFormatException e) {
        // Do your thing if the check fails
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      相关资源
      最近更新 更多