---
title: "Idiot's Note Four: 循环中continue和“if ”的细节注意"
author: "danielhjd"
date: "2011-06-30T18:04:54Z"
tags: []
categories: ["编程语言"]
slug: "idiot-s-note-four-continue-if"
draft: false
lastmod: "2011-06-30T18:06:25Z"
id: 1111401
url: "https://danielhjd.iteye.com/blog/1111401"
---

先查看代码：

```
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;}**