Java 中断
Java中的break语句主要用于以下两种情况。- Break 退出循环并跳出循环(for 和 while)。
- Break 语句退出 switch 语句中的一个 case。
句法
break;
例子
public class Driver1 {
public static void main(String[] args) {
// Testing break statement in while loop
System.out.println("Test Break statement in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
break;
}
System.out.println(i++);
}
}
}
输出
While 循环中的 Test Break 语句 0 1
Java 继续
Java中的continue语句常用于以下情况。- 它跳过以下语句并移至for循环中的下一次迭代。
- 在 while 循环中继续跳转以下语句并跳转到条件语句。
句法
continue;
例子
public class Driver2 {
public static void main(String[] args) {
// Testing continue statement in while loop
System.out.println("Test Continue in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
i++;
continue;
}
System.out.println(i++);
}
}
}
输出
在 While 循环中继续测试 0 1 3 4
continue 和 break 的区别
break 和 continue 之间的显着区别在于 break 立即退出循环。一旦执行了 break 语句,循环将不会再次运行。但是,在执行 continue 语句后,将仅针对当前迭代跳过以下代码行。循环将再次开始执行。在 While 循环中中断并继续
Break 和 Continue 都可以在while循环中使用。让我们看下面的例子来有个清晰的认识。例子
public class Driver {
public static void main(String[] args) {
// Testing both break and continue statements side by side
String [] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Test Break statement in While loop");
System.out.println("\nWorking Days:\n");
int i = 0;
while (i < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
i++;
break;
// Not any working day will be printed
// because the loop breaks on Sunday
// once the loop breaks it moves out of the loop
}
System.out.println(weekdays[i++]);
}
System.out.println("\nTest Continue statement in While loop");
System.out.println("\nWorking Days:\n");
int j = 0;
while (j < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
j++;
continue;
// All the working/business days will be printed
// when the loop encounters Saturday or Sunday
// it skips that iteration and continues to the next iteration
}
System.out.println(weekdays[i++]);
}
// A test case for continue statement using for loop
System.out.println("\nTest Continue in For loop");
for (int x = 0; x < 5; x++) {
if (x == 2)
continue;
System.out.println(x);
}
}
}
输出
在 While 循环中测试 Break 语句工作日:在 While 循环中测试 Continue 语句工作日:周一周二周三周四周五周五在 For 循环中测试 Continue 0 1 3 4
GO TO FULL VERSION