pro*_*owl 4 java integer numbers function
是否可以使用返回Integer或Float的函数?如果可能的话,我想让2个函数成为一个函数:
private static Integer parseStringFormatInt(String val){
System.out.println(Integer.parseInt(val.substring(0, val.indexOf("."))));
return Integer.parseInt(val.substring(0, val.indexOf(".")));
}
private static Float parseStringFormatFloat(String val){
System.out.println(Float.parseFloat(val.substring(0, val.indexOf("."))));
return Float.parseFloat(val.substring(0, val.indexOf(".")));
}
Run Code Online (Sandbox Code Playgroud)
将返回类型设置为Number两者,Float并且Integer是Number下面的子类型
private static Number parseStringFormatNumber(String val){
//Based on your conditions return either Float or Integer values
}
Run Code Online (Sandbox Code Playgroud)
您还可以让instanceof操作员对返回值进行测试,以获得返回值的确切类型.即Float或Integer
if(returnedValue instanceof Float)
{
// type cast the returned Float value and make use of it
}
else if(returnedValue instanceof Integer)
{
// type cast the returned Integer value and make use of it
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 Number 作为返回类型,或使该方法通用
static <T extends Number> T parseString(String str, Class<T> cls) {
if (cls == Float.class) {
return (T) Float.valueOf(str);
} else if (cls == Integer.class) {
return (T) Integer.valueOf(str);
}
throw new IllegalArgumentException();
}
Run Code Online (Sandbox Code Playgroud)