First of all, your if
condition will certainly fail, because the object
reference actually points to a String object. So, they are not instances of any integer
or double
.
To check whether a string can be converted to integer
or double
, you can either follow the approach in @Bedwyr's answer, or if you don't want to use try-catch
, as I assume from your comments there (Actually, I don't understand why you don't want to use them), you can use a little bit of 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;
}
But, understand that, Integer.parseInt
and Double.parseDouble
is the right way to do this. This is just an alternate approach.