java - 为什么我的 else 语句在 'while-loop' 中执行,但不在 JAVA 中的'for-loop' 中执行
问题描述
我对 Java 有点陌生,试图通过复数视觉和几本参考书自学 - “一日学习 Java,学得好”。
我遇到了一种特殊情况,在“while 循环”内,我的 else 块执行大于 100 的结果。但是对于类似的东西,在“for 循环”语句内,else 部分不执行一点也不。我很想更多地了解为什么我在 while 循环中所做的工作按我的预期工作,但不是当我在 for 循环中做类似的事情时。
谢谢你。
While 循环: - 完美执行,if 语句和 else 语句
int wVal = 1;
while(wVal < 100) {
System.out.println(wVal);
wVal *= 2;
if (wVal <100 ){
System.out.println("going back to the top to check if wVal is less than 100");
}else{
System.out.println("We hit more than a hundred!!!");
}
}
For-Loop: - 只执行语句的“if”部分。不确定为什么没有执行 else 语句。
System.out.println("Entering the for loop for lVal2");
for (int lVal2 = 1; lVal2 <100; lVal2 *=2 ){
if (lVal2 < 100) {
System.out.println("The value of lVal2 is currently: " + lVal2);
System.out.println("The multiplication is being done ....");
System.out.println("Going back to the to the top unless we hit 100");
}else{
System.out.println("We hit more than a hundred!!!!");
}
}
解决方案
for 循环在每个循环周期结束时执行最后一条语句。这意味着在 for 循环中,lval2
被加倍,并立即检查它是否大于 100(for 循环的条件部分)。这意味着如果它大于 100,它甚至不会再次进入循环,因此不会到达 else 语句。
For 循环在循环开始时执行一次初始化(第一部分)。然后他们在循环的每个循环之前检查条件(第二部分),并在每个循环结束时执行增量(第三部分)。
希望这有帮助。
推荐阅读
- java - 在特定步骤下的单个处理器中的多个实体管理器(对多个数据库连接使用不同的数据源):Spring Batch
- python - Python - 在for循环中屏蔽?
- javascript - 如何修复 Lerna Monorepo 中的 VSCode 导入路径建议?
- php - 读取 MySQL blob 字段并转换为 JSON for android webservice
- apache-camel - Camel REST DSL - 内容长度分隔的消息体过早结束
- excel - 另存为 PDF 宏,带下拉菜单
- javascript - 如何使用角度根据父母和孩子获取密钥
- python - 以两种不同的方式排序。但是得到错误的输出
- javascript - 使用 TypeScript 键入的样式系统道具
- android - 使用选项卡和输入键而不是鼠标单击时在片段中使用 AndroidStudio 仿真 On_Click 事件