ITeye博客

Idiot's Note Four: 循环中continue和“if ”的细节注意

danielhjd · 2011-06-30 18:04 · Java · 编程语言 · Markdown

先查看代码:

public class ContinueTesting {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("peter piper picked a peck of pickled peppers");
		int x=0;
		System.out.println(sb.length());
		for (int i=0;i<sb.length();i++){
			if(sb.charAt(i)!='p')
				continue;
				x++;	
				sb.setCharAt(i, 'O');
		}
		System.out.println("found "+x+" p's in the string");
		System.out.println(sb);
	}

}

 输出结果:

44
found 9 p's in the string
Oeter OiOer Oicked a Oeck of Oickled OeOOers

 

含continue的代码块:

for (int i=0;i<sb.length();i++){
			if(sb.charAt(i)!='p')
				continue;
				x++;	
				sb.setCharAt(i, 'O');
		}

 

continue的功能:

终止当前的这轮循环,即跳过continue语句后面的剩余的语句,并计算和判断循环条件,决定是否进入下一轮循环。

 

注意:

if(sb.charAt(i)!='p') 后面不接**{}也是可以通过编译的,默认if后面的statement为{}**内容.. 此处程序相当于

if(sb.charAt(i)!='p')  {continue;}

评论(0)

暂无评论。

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