代码举例
// 嵌套循环
if (p instanceof Architect) {
if (numOfArc >= 1) {
throw new TeamException("每个团队中最多只能有一名架构师");
}
} else if (p instanceof Designer) {
if (numOfDes >= 2) {
throw new TeamException("团队中至多只能有两名设计师");
}
} else if (p instanceof Programmer) {
if (numOfPro >= 3) {
throw new TeamException("团队中至多只能有三名程序员");
}
}
// &&
if (p instanceof Architect && numOfArc >= 1) {
throw new TeamException("每个团队中最多只能有一名架构师");
} else if (p instanceof Designer && numOfDes >= 2) {
throw new TeamException("团队中至多只能有两名设计师");
} else if (p instanceof Programmer && numOfPro >= 3) {
throw new TeamException("团队中至多只能有三名程序员");
}
其中,Architect继承于Designer,Designer继承于Programmer;
1、嵌套循环中,如果p instanceof Architect为true,numOfArc >= 1 为false,结果不会抛出异常throw new TeamException("每个团队中最多只能有一名架构师"),下面的else if都不会被执行。
2、&&中,如果p instanceof Architect为true,numOfAr

本文探讨了Java中嵌套循环和使用逻辑&&进行循环判断时的差异,特别是在涉及类继承关系时可能导致的逻辑错误。当使用嵌套循环时,如果实例属于特定子类但不满足其他条件,程序不会抛出异常。而使用&&时,即使子类条件不满足,程序仍可能继续执行父类的判断,引发逻辑错误。因此,建议在编写代码时清晰梳理逻辑,避免使用&&导致的错误判断。
最低0.47元/天 解锁文章
979

被折叠的 条评论
为什么被折叠?



