分支语句:if和switch
循环语句:while,do-while和for
跳转语句:break,continue ,return和throw
8.1分支语句
8.1.1if语句
1.if
int score = 95;
if (score >= 85) {
System.out.println("你真优秀");
}
if (score <60) {
System.out.println("你不及格");
2.if-else
int score = 95;
if (score < 60) {
System.out.println("不及格");
} else {
System.out.println("及格");
3.else-if
int testScore = 76;
char grade;
if (testScore >= 90) {
grade = 'A';
} else if(testScore >=80) {
grade = 'B';
} else if(testScore >=60){
grade = 'C';
} else {
grade = 'D'
}
System.out.println("Grade = " + grade);
8.1.2switch语句
int testScore = 75;
char grade;
switch(testScore / 10) {
case 9:
grade = '优良';
break;
case 8:
grade = '良好';
break;
case 7 :
case 6 :
grade = '中';
break;
default:
grade = ‘差’;
}
System.out.println("Grade = " + grade);
8.2循环语句
8.2.1while循环
int i = 0;
while (i * i< 100000) {
i++;
}
System.out.println("i = " + i);
System.out.println("i * i = " + (i*i));
8.2.2do-while循环
int i = 0;
do{
i++;
} while(i * i < 10000);
System.out.println("i = " + i);
System.out.println("i * i = " + (i*i));
8.2.3for语句
int x;
int y;
for(x = 0,y = 0; x < y;x++,y--) {
System.out.printf("(x,y) = (%d,%d)",x,y);
//打印一个换行符,实现换行
System.out.println();
}
8.2.4增强for语句
//声明并初始化int数组;
int [] numbers = { 43, 32, 53, 54, 75, 7, 10 };
System.out.printf("------for----------");
//for语句
for(int i = 0;i < numbers.length; i++)
System.out.println("Count is :" + number[i]);
}
--------------------------------------------------------------------------------------------
//声明并初始化int数组
int [] numbers = { 43, 32, 53, 54, 75, 7, 10 };
System.out.printf("-------------增强for-------------------");
//增强for语句
for(int item : numbers){
System.out.println("Count is :" + item);
}
8.3跳转语句
8.3.1break语句
·break的作用是强行退出循环体,不在执行循环体中剩余的语句
例子一:
int [] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < numbers.length; i++) {
if(i == 3){
//跳出循环
break;
}
System.out.printf("Count is :" + i);
}
例子二:
label1: for(int x = 0;x < 5; x++) {
for(int y = 5;y > 0; y--) {
if (y == x) {
//跳转到label1指向的循环
break label1;
}
System.out.printf("(x,y) = (%d,%d)",x,y);
//打印一个换行符,实现换行
System.out.println();
}
}
System.out.println("Game over");、
当x==y时结束循环
8.3.2continue语句
continue用来结束本次循环,跳过循环体中尚未执行的语句,接着进行终止条件的判断,以决定是否继续循环。对于for语句,在进行终止条件的判断前,还要先执行迭代语句。
例子1:
int [] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i<numbers.length; i++) {
if(i == 3) {
continue;
}
System.out.println("Count is :" + i);
}
例子2:
label1:for (int x = 0; x < 5 ;x++) {
for (int y = 5; y > 0 ;y++;) {
if (y == x) {
continue label1;
}
System.out.printf("(x,y) = (%d,%d)", x, y);
System.out.println();
}
}
System.out.println("Game over!");\
默认情况下continue只会跳出内循环,即跳过了x==y