Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Type before casting in java

I am casting my String variables to integer and double. I want to check whether the String variable contains valid Integer or Double value at runtime.

I us following code but it not works for me.

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
}
like image 535
Syed Muhammad Mubashir Avatar asked Jul 05 '26 00:07

Syed Muhammad Mubashir


2 Answers

Try to parse the int and catch the exception if it fails:

String var1="5.5";

try {
 qt += Integer.parseInt( var1);
}    
catch (NumberFormatException nfe) {
// wasn't an int
}
like image 137
blank Avatar answered Jul 07 '26 13:07

blank


You can use patterns to detect if a string is an integer or not :

  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
  }

You will have to find the correct pattern (I haven't used them for awhile) or someone could edit my answer with the correct pattern.

*EDIT** : Found a pattern for you. edited the code. I did not test it but it is taken from java2s site which also offer an even more elgant approach (copied from the site) :

 public static boolean isNumeric(String string) {
      return string.matches("^[-+]?\\d+(\\.\\d+)?$");
  }
like image 41
giorashc Avatar answered Jul 07 '26 14:07

giorashc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!