java - 在强制转换之前如何检查类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13579802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check Type before casting in java
提问by Syed Muhammad Mubashir
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.
我将我的字符串变量转换为整数和双精度。我想在运行时检查 String 变量是否包含有效的 Integer 或 Double 值。
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
}
回答by blank
Try to parse the int and catch the exception if it fails:
尝试解析 int 并在失败时捕获异常:
String var1="5.5";
try {
qt += Integer.parseInt( var1);
}
catch (NumberFormatException nfe) {
// wasn't an int
}
回答by Rohit Jain
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
.
首先,你的if
条件肯定会失败,因为object
引用实际上指向一个 String 对象。因此,它们不是 anyinteger
或 的实例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
: -
要检查字符串是否可以转换为integer
或double
,您可以按照@Bedwyr 的答案中的方法,或者如果您不想使用try-catch
,正如我从您那里的评论中推测的那样(实际上,我不明白您为什么不这样做不想使用它们),你可以使用一点点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.
但是,理解,Integer.parseInt
并且Double.parseDouble
是做的正确方法。这只是一种替代方法。
回答by giorashc
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) :
*编辑**:为您找到了一个模式。编辑了代码。我没有测试它,但它取自 java2s 站点,该站点还提供了更优雅的方法(从站点复制):
public static boolean isNumeric(String string) {
return string.matches("^[-+]?\d+(\.\d+)?$");
}
回答by sp00m
Maybe regexps could suit your needs:
也许正则表达式可以满足您的需求:
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));
}
Prints:
印刷:
false
true
true
false
回答by Thorkil Holm-Jacobsen
Integer.parseInt
and Double.parseDouble
return the integer/double value of the String
. If the String
is not a valid number, the method will thrown a NumberFormatException
.
Integer.parseInt
并Double.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
}
回答by Nils De Winter
You can also check if your string contains a dot/point :
您还可以检查您的字符串是否包含点/点:
String var1="5.5";
if (var1.contains(".")){
// it should be a double
}else{
// int
}