下面的例子是“表达式计算器”的部分代码
这种写代码的方式,类似于用switch,而continue则相当于break:
for(int index=0; index<expLength; index++) {
char c=expression[index];
if(Character.isDigit(c))
{
//数字
digitStr.append(c);
prevIsDigit=true;
continue;
}
if(c=='-'&&prevIsDigit==false)
{
//negative digital 负数
digitStr.append(c);
prevIsDigit=false;
continue;
}
//操作字符,同时digitStr中为空
if((!Character.isDigit(c))&&digitStr.length()==0)
{
prevIsDigit=false;
doWith(c);
continue;
}
//操作字符,同时digitStr中不为空,可以将digitStr放入digitStack中
if((!Character.isDigit(c))&&digitStr.length()!=0)
{
Double temp=Double.valueOf(digitStr.toString());
digitStack.push(temp);
digitStr.delete(0, digitStr.length());
prevIsDigit=false;
doWith(c);
continue;
}
}
又例如:
public void doWith(char opChar)
{
if (opChar=='('||opChar==')')
{
doBracket(opChar);
}
if(opChar=='#')
{
doEndChar(opChar);
}
if(opChar=='+'||opChar=='-'||opChar=='*'||opChar=='/')
{
doOperator(opChar);
}
}
在这些多分支语句中没有使用else,只判定在某确定的条件下的行为,而不模糊的使用else。原因自己总结如下:
①使用else容易有漏网之鱼,导致出现一些莫名奇妙的错误(其实是自己糊涂);
②在算法改变时代码修改的过程中也容易出问题;
③代码维护不易,尤其是使用else的代码清晰度较低,没有那么明确。