在我们判断变量的时候通常要做3次判断,简单举个例子吧
1.判断是否存在
if(str==null)
2.判断长度是否为零
if(str.length()==0)
3.判断是否能转换成自己需要的格式(这里整型为例)
if(str.matches("[0-9]+"))
那么问题来了,该如何来写呢?
方法一:
if(str!=null){
if(str.length()!=0){
if(str.matches("[0-9]+")){
System.out.println("成功");
}
else{
System.out.println("无法转换");
}
}
else{
System.out.println("空串");
}
}
else{
System.out.println("空指针");
}
这种写法,我只能说3个字!非人类!!可读性最差,写起来最麻烦!
方法二:
try{
if(Integer.parseInt(str)>0){
System.out.println("成功");
}
}
catch(NullPointerException npe){
System.out.println("空指针异常");
}
catch(KongZiFuChuanException kzfce){
System.out.println("空串异常");
}
catch(NumberFormatException nfe){
System.out.println("无法转换异常");
}
这样写的话,可读性提高了,但是在创建异常对象的时候是会调用栈的,对性能会有影响!(请忽略那个空串异常,随意起的名字,毕竟没有这个异常)
方法三:
if(str==null){
System.out.println("空指针");
return ;
}
if(str.length()==0){
System.out.println("空串");
return ;
}
if(!str.matches("[0-9]+")){
System.out.println("无法转换");
return ;
}
这是标准写法,按照机器执行代码的顺序一步步执行,可读性高,堪称完美!
相信大家都有自己的见解了!
以上!