continue,break

本文通过两个示例展示了Java中break和continue关键字的用法。break用于立即退出整个循环,而continue则跳过当前迭代继续下一次循环。示例代码演示了当循环变量等于特定值时如何使用这些关键字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The break and continue keywords are used to stop either the entire loop
(break) or just the current iteration (continue).


public class ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Inside loop, i = "+i);
if (i == 3) {
System.out.println("if is true: i == 3");
continue;
// compile error: says it's unreachable
// System.out.println("after the continue statement");
}
// more loop code, that won't be reached when the above if test is true
System.out.println("after the if statement, still inside loop");
}
System.out.println("out of loop");
}
}


Output:

[b]Inside loop, i = 0
after the if statement, still inside loop
Inside loop, i = 1
after the if statement, still inside loop
Inside loop, i = 2
after the if statement, still inside loop
Inside loop, i = 3
if is true: i == 3
Inside loop, i = 4
after the if statement, still inside loop
out of loop[/b]



public class ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Inside loop, i = "+i);
if (i == 3) {
System.out.println("if is true: i == 3");
break;
// compile error: says it's unreachable
// System.out.println("after the continue statement");
}
// more loop code, that won't be reached when the above if test is true
System.out.println("after the if statement, still inside loop");
}
System.out.println("out of loop");
}
}


Output:

[b]Inside loop, i = 0
after the if statement, still inside loop
Inside loop, i = 1
after the if statement, still inside loop
Inside loop, i = 2
after the if statement, still inside loop
Inside loop, i = 3
if is true: i == 3
out of loop[/b]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值