`
fantasyday
  • 浏览: 32942 次
  • 性别: Icon_minigender_1
  • 来自: 东京
社区版块
存档分类
最新评论

continue,break

    博客分类:
  • Java
 
阅读更多
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:

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





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:

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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics