Scala 循环中实现 Continue 和 Break:递归函数与条件语句
在 Scala 中,可以使用递归函数来模拟循环,并使用条件语句来实现 continue 和 break 的功能。\n\n下面是一个示例代码,演示如何在循环内同时实现 continue 和 break:\n\nscala\ndef loopWithBreakAndContinue(): Unit = {\n var i = 0\n var shouldContinue = true\n while (i < 10 && shouldContinue) {\n if (i == 3) {\n // 实现 continue 的功能\n i += 1\n shouldContinue = true\n } else if (i == 7) {\n // 实现 break 的功能\n shouldContinue = false\n } else {\n // 循环体内的代码\n println(i)\n i += 1\n }\n }\n}\n\nloopWithBreakAndContinue()\n\n\n在上述代码中,使用一个变量 shouldContinue 来控制循环的继续与中断。当 shouldContinue 为 true 时,循环继续执行;当 shouldContinue 为 false 时,循环中断。\n\n当 i 等于 3 时,设置 shouldContinue 为 true,实现了 continue 的功能,跳过当前循环体内的代码,进入下一次循环。\n\n当 i 等于 7 时,设置 shouldContinue 为 false,实现了 break 的功能,中断循环。
原文地址: https://www.cveoy.top/t/topic/pBMs 著作权归作者所有。请勿转载和采集!