ITeye博客

continue,break

fantasyday · 2009-07-16 13:25 · Java · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。