在计算机编程中,循环用于重复代码块。例如,如果要显示一条消息100次,则可以使用循环。这只是一个简单的例子。使用循环可以实现更多目标。
在上一教程中,您了解了Java for循环。在这里,您将学习while和do...while循环。
Java while循环
Java while循环用于运行特定代码,直到满足特定条件为止。 while循环的语法为:
这里,
while循环评估括号()内的textExpression 。
如果textExpression评估为true ,则执行while循环内的代码。
再次评估textExpression 。
这个过程一直持续到textExpression为false为止。
当textExpression计算为false ,循环停止。
要了解有关条件的更多信息,请访问Java关系和逻辑运算符。
While循环流程图
Java while循环流程图
示例1:显示从1到5的数字
输出
该程序的工作原理如下。
Iteration
Variable
Condition: i <= n
Action
1st
i = 1
n = 5
true
1 is printed.
i is increased to 2.
2nd
i = 2
n = 5
true
2 is printed.
i is increased to 3.
3rd
i = 3
n = 5
true
3 is printed.
i is increased to 4.
4th
i = 4
n = 5
true
4 is printed.
i is increased to 5.
5th
i = 5
n = 5
true
5 is printed.
i is increased to 6.
6th
i = 6
n = 5
false
The loop is terminated
示例2:仅正数之和
输出
在上面的程序中,我们使用了Scanner类从用户那里获取输入。在这里, nextInt()从用户处获取整数输入。
while循环继续进行,直到用户输入一个负数。在每次迭代期间,将用户输入的数字添加到sum变量中。
当用户输入负数时,循环终止。最后,显示总和。
Java do … while循环
do...while循环类似于while循环。但是, do...while循环的主体在检查测试表达式之前执行一次。例如,
这里,
循环的主体首先执行。然后评估textExpression 。
如果textExpression评估为true ,则将再次执行do语句内的循环主体。
再次评估textExpression 。
如果textExpression评估为true ,则将再次执行do语句内的循环主体。
这个过程一直持续到textExpression的值为false为止。然后循环停止。
do … while循环流程图
Java流程图做while循环
让我们看看do...while循环的工作原理。
示例3:显示从1到5的数字
输出
该程序的工作原理如下。
Iteration
Variable
Condition: i <= n
Action
i = 1
n = 5
not checked
1 is printed.
i is increased to 2.
1st
i = 2
n = 5
true
2 is printed.
i is increased to 3.
2nd
i = 3
n = 5
true
3 is printed.
i is increased to 4.
3rd
i = 4
n = 5
true
4 is printed.
i is increased to 5.
4th
i = 5
n = 5
true
6 is printed.
i is increased to 6.
5th
i = 6
n = 5
false
The loop is terminated
示例4:正数之和
输出1
在此,用户输入一个正数,该数将添加到sum变量中。这个过程一直持续到负数为止。当数字为负数时,循环终止并显示总和,而不添加负数。
输出2
用户在此处输入一个负数。测试条件将为false但是循环内部的代码将执行一次。
无限while循环
如果循环的条件始终为true ,则循环将运行无限次(直到内存已满)。例如,
这是一个无限的do...while循环的示例。
在上述程序中, textExpression始终为true 。因此,循环体将运行无限次。
for和while循环
当迭代次数已知时,使用for循环。例如,
当迭代次数未知时,通常使用while和do...while循环。例如,