Sey*_*emi 9 java floating-point try-catch
有一些情况我需要将字符串转换为浮点数或其他一些数值数据类型,但有可能获得一些不可转换的值,如" - "或"/",我无法预先验证所有值以删除他们.我想避免使用try/catch这个问题,还有其他方法在java中进行正确的转换吗?类似于C#的东西TryParse
?
不幸的是,Java中没有这样的方法.Java中没有out参数,因此编写这样的方法需要返回一个null Float来表示错误,或者传递一个可以通过该方法修改的FloatHolder对象:
public class FloatHolder {
private float value;
public void setValue(float value) {
this.value = value;
}
public float getValue() {
return this.value;
}
}
public static boolean tryParseFloat(String s, FloatHolder holder) {
try {
float value = Float.parseFloat(s);
holder.setValue(value);
}
catch (NumberFormatException e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我能想到的最简单的事情是java.util.Scanner
.但是,此方法需要为每个String提供一个新的Scanner实例.
String data = ...;
Scanner n = new Scanner(data);
if(n.hasNextInt()){//check if the next chars are integer
int i = n.nextInt();
}else{
}
Run Code Online (Sandbox Code Playgroud)
接下来,您可以编写一个正则表达式模式,用于检查字符串(复杂以使失败的值太大),然后在检查字符串后调用Integer.parseInt().
Pattern p = Pattern.compile("insert regex to test string here");
String data = ...;
Matcher m = p.matcher(data);
//warning depending on regex used this may
//only check part of the string
if(m.matches()){
int i = Integer.parseInt(data);
}
Run Code Online (Sandbox Code Playgroud)
但是这两个都解析了两次字符串,一次测试字符串,第二次解析值.根据您获取无效字符串捕获异常的频率可能会更快.
归档时间: |
|
查看次数: |
8425 次 |
最近记录: |