您的位置:首页 > 编程语言 > Java开发

JAVA那点事,慢慢来说之六

2009-05-28 21:17 337 查看
一、条件语句

1)if语句
根据不同条件,执行不同语句
a)if
b)if... else...
c) if... else if...
d) if... else if... else if...
e) if... else if... else if... else

b)switch 语句
java中switch语句只能探测int类型值。
switch(){
case xx :
... .
case xx :
... .
default:
... .
}

eg.

public class TestSwich {
public static void main(String[] args){
int i = 8;
switch(i){
case 8:
case 3:
case 2:
System.out.println("C");
break;
case 9:
System.out.println("D");
break;
default:
System.out.println("ERROR");

}
}
}

二、循环语句

1)for语句

for (exp1;exp2;exp3){
语句;
...;
}

eg.
public class TestFor {
public static void main(String args[]){
long result = 0;
long f = 1;
for (int i = 1 ; i <= 10 ; i++) {
f = f*i;
result += f;
}
System.out.println("result=" + result);
}
}

2)while & do while 语句
a) while

while(exp1){
语句;
...;
}
先判断逻辑表达式exp1的值,再执行语句;
b) do while
do {
语句;
...;
}while(exp1);

先执行语句,再判断逻辑表达式exp2的值。

3) break & continue
break :终止某个语句块的执行,可以强行退出循环;
continue:终止某次循环过程,跳过循环体中continue下面的未执行语句,开始下一次循环。
eg.
//1~100 内前5个被3整除的数
public class TestBreak{
public static void main(String args[]){
int num = 0 ,i = 1;
while ( i <= 100) {
if (i%3==0) {
System.out.print(i + " ");
num++;
}
if (num == 5) {
break;
}
i++;
}
}
}
//输出101~200内的质数
public class TestContinue{
public static void main(String args[]){

for (int i = 101 ; i < 200 ; i+=2) {
boolean f = true;
for (int j=2 ;j < i ; j++) {
if (i % j == 0 ) {
f = false;
break;
}
}
fi (!f){continue;}
System.out.print(" "+ i);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: