第 5 节 Java程序逻辑控制
分支结构
if (布尔表达式) {
程序语句;
}if (布尔表达式) {
程序语句;
} else {
程序语句;
}if (布尔表达式1) {
程序语句;
} else if(布尔表达式2) {
程序语句;
} else if(布尔表达式3) {
程序语句;
} ...循环结构
循环控制
最后更新于
if (布尔表达式) {
程序语句;
}if (布尔表达式) {
程序语句;
} else {
程序语句;
}if (布尔表达式1) {
程序语句;
} else if(布尔表达式2) {
程序语句;
} else if(布尔表达式3) {
程序语句;
} ...最后更新于
double score = 90;
if (score > 60.0) {
System.out.println("及格了!");
}double score = 90;
if (score > 60.0) {
System.out.println("及格了!");
} else {
System.out.println("没及格!");
}double score = 90;
if (score < 60.0) {
System.out.println("没及格!");
} else if (score >= 60 && score <= 90) {
System.out.println("中等成绩!");
} else if (score > 90 && score <= 100) {
System.out.println("优秀成绩!");
} else {
System.out.println("没有这样的成绩!");
}switch (整数 | 字符 | 枚举 | String) {
case 内容 : {
内容满足时执行;
[break;]
}
case 内容 : {
内容满足时执行;
[break;]
}
case 内容 : {
内容满足时执行;
[break;]
} ...
[default : {
内容都不满足时执行;
[break;]
}]
}int ch = 2;
switch (ch) {
case 2: {
System.out.println("内容是2");
break;
}
case 1: {
System.out.println("内容是1");
break;
}
case 3: {
System.out.println("内容是3");
break;
}
default: {
System.out.println("没有匹配内容");
break;
}
}String str = "HELLO";
switch (str) {
case "HELLO": {
System.out.println("内容是HELLO");
break;
}
case "hello": {
System.out.println("内容是hello");
break;
}
case "world": {
System.out.println("内容是world");
break;
}
default: {
System.out.println("没有匹配内容");
break;
}
}while (循环判断) {
循环语句;
修改循环结束条件;
}do {
循环语句;
修改循环结束条件;
} while (循环判断);int sum = 0; //保存总和
int current = 1; //循环的初始化条件
while (current <= 100) { //循环的结束条件
sum += current; //累加
current ++;
}
System.out.println(sum);int sum = 0; //保存总和
int current = 1; //循环的初始化条件
do {
sum += current; //累加
current ++;
} while (current <= 100); //循环的结束条件
System.out.println(sum);for (循环初始化条件; 循环判断; 循环条件改变) {
循环语句;
}int sum = 0; //保存总和
for (int current = 1; current <= 100; current ++) {
sum += current;
}
System.out.println(sum);int sum = 0; //保存总和
int current = 1;
for (; current <= 100;) {
sum += current;
current ++;
}
System.out.println(sum);for (int i = 1; i <= 10; i ++) {
System.out.print("开始看第" + i + "本书");
for (int j = 1; j <= 20; j ++) {
System.out.print("看第" + j + "页");
}
System.out.println();
}for (int i = 1; i <= 9; i ++) {
for (int j = 1; j <= i; j ++) {
System.out.print(i + " * " + j + " = " + (i * j) + "\t");
}
System.out.println();
}for (int i = 0; i < 10; i ++) {
if (i == 3) {
continue;
}
System.out.println("i = " + i);
}for (int i = 0; i < 10; i ++) {
if (i == 3) {
break;
}
System.out.println("i = " + i);
}