Java-循环控制
在某些情况下,您需要多次执行一个代码块。通常,语句是按顺序执行的:函数的第一个语句首先执行,然后第二个执行,依此类推。
编程语言提供了各种控制结构,允许更复杂的执行路径。
循环语句使我们可以多次执行一个语句或一组语句,以下是大多数编程语言中循环语句的一般形式-
Java编程语言提供了以下类型的循环来处理循环需求。单击以下链接以查看其详细信息。
Sr.No.
Loop & Description
1
while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
2
for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3
do…while loop
Like a while statement, except that it tests the condition at the end of the loop body.
循环控制语句
循环控制语句从其正常顺序更改执行。当执行离开作用域时,在该作用域中创建的所有自动对象都将被销毁。
Java支持以下控制语句。单击以下链接以查看其详细信息。
Sr.No.
Control Statement & Description
1
break statement
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
2
continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
增强了Java中的for循环
从Java 5开始,引入了增强的for循环。这主要用于遍历元素(包括数组)的集合。
句法
以下是增强的for循环的语法-
声明-新声明的块变量的类型与您正在访问的数组的元素兼容。该变量将在for块中可用,并且其值将与当前数组元素相同。
表达式-计算结果为您需要遍历的数组。该表达式可以是数组变量或返回数组的方法调用。
例
这将产生以下结果-
输出
接下来是什么?
在下一章中,我们将学习Java编程中的决策语句。