有人能告诉我break语句和continue语句的区别吗?
当前回答
break语句跳出循环(要执行的下一个语句是右大括号之后的第一个语句),而continue语句在下一个迭代中开始循环。
其他回答
break语句存在于当前循环控制结构中,并跳转到它后面,而continue语句也退出,但跳转回循环条件。
下面是break的语义:
int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// find 9
for(int i = 0; i < a.Length; i++)
{
if (a[i] == 9)
goto goBreak;
Console.WriteLine(a[i].ToString());
}
goBreak:;
下面是continue的语义:
int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// skip all odds
for(int i = 0; i < a.Length; i++)
{
if (a[i] % 2 == 1)
goto goContinue;
Console.WriteLine(a[i].ToString());
goContinue:;
}
答得好,简单准确。
我会添加一个代码示例。
C:\oreyes\samples\java\breakcontinue>type BreakContinue.java
class BreakContinue {
public static void main( String [] args ) {
for( int i = 0 ; i < 10 ; i++ ) {
if( i % 2 == 0) { // if pair, will jump
continue; // don't go to "System.out.print" below.
}
System.out.println("The number is " + i );
if( i == 7 ) {
break; // will end the execution, 8,9 wont be processed
}
}
}
}
C:\oreyes\samples\java\breakcontinue>java BreakContinue
The number is 1
The number is 3
The number is 5
The number is 7
简单的程序,了解继续和中断之间的区别
当使用continue时
public static void main(String[] args) {
System.out.println("HelloWorld");
for (int i = 0; i < 5; i++){
System.out.println("Start For loop i = " + i);
if(i==2){
System.out.println("Inside if Statement for i = "+i);
continue;
}
System.out.println("End For loop i = " + i);
}
System.out.println("Completely out of For loop");
}
OutPut:
HelloWorld
Start For loop i = 0
End For loop i = 0
Start For loop i = 1
End For loop i = 1
Start For loop i = 2
Inside if Statement for i = 2
Start For loop i = 3
End For loop i = 3
Start For loop i = 4
End For loop i = 4
Completely out of For loop
什么时候使用break
public static void main(String[] args) {
System.out.println("HelloWorld");
for (int i = 0; i < 5; i++){
System.out.println("Start For loop i = " + i);
if(i==2){
System.out.println("Inside if Statement for i = "+i);
break;
}
System.out.println("End For loop i = " + i);
}
System.out.println("Completely out of For loop");
}
Output:
HelloWorld
Start For loop i = 0
End For loop i = 0
Start For loop i = 1
End For loop i = 1
Start For loop i = 2
Inside if Statement for i = 2
Completely out of For loop
继续声明停止滴定,开始下一次滴定 例:
System.out.println("continue when i is 2:");
for (int i = 1; i <= 3; i++) {
if (i == 2) {
System.out.print("[continue]");
continue;
}
System.out.print("[i:" + i + "]");
}
和Break语句停止循环或退出循环
推荐文章
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母
- Mockito.any()传递带有泛型的接口
- 在IntelliJ 10.5中运行测试时,出现“NoSuchMethodError: org.hamcrest. matcher . descripbemismatch”
- 使用String.split()和多个分隔符
- Java数组有最大大小吗?
- 在Android中将字符串转换为Uri
- 从JSON生成Java类?
- 为什么java.util.Set没有get(int index)?
- Swing和AWT的区别是什么?
- 为什么Java流是一次性的?
- 四舍五入BigDecimal *总是*有两位小数点后
- 设计模式:工厂vs工厂方法vs抽象工厂
- Java:检查enum是否包含给定的字符串?
- 它的意思是:序列化类没有声明一个静态的最终serialVersionUID字段?