147 lines
2.4 KiB
Markdown
147 lines
2.4 KiB
Markdown
---
|
||
id: 控制语句
|
||
title: 控制语句
|
||
sidebar_position: 3
|
||
data: 2022年4月26日
|
||
---
|
||
|
||
Java 中的控制语句其实和 C 一样,会涉及刀包括 **if-else、while、do-while、for、return、break、switch**。
|
||
|
||
## 条件语句
|
||
|
||
### if 语句
|
||
|
||
```java
|
||
int a = 10;
|
||
|
||
if(a > 10){
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
```
|
||
|
||
### if...else 语句
|
||
|
||
```java
|
||
int a = 10;
|
||
int b = 11;
|
||
|
||
if(a >= b){
|
||
System.out.println("a >= b");
|
||
}else{
|
||
System.out.println("a < b");
|
||
}
|
||
```
|
||
|
||
### if...else if 多分支语句
|
||
|
||
```java
|
||
int x = 40;
|
||
|
||
if(x > 60) {
|
||
System.out.println("x的值大于60");
|
||
} else if (x > 30) {
|
||
System.out.println("x的值大于30但小于60");
|
||
} else if (x > 0) {
|
||
System.out.println("x的值大于0但小于30");
|
||
} else {
|
||
System.out.println("x的值小于等于0");
|
||
}
|
||
```
|
||
|
||
### switch 多分支语句
|
||
|
||
```java
|
||
switch (week) {
|
||
case 1:
|
||
System.out.println("Monday");
|
||
break;
|
||
case 2:
|
||
System.out.println("Tuesday");
|
||
break;
|
||
case 3:
|
||
System.out.println("Wednesday");
|
||
break;
|
||
case 4:
|
||
System.out.println("Thursday");
|
||
break;
|
||
case 5:
|
||
System.out.println("Friday");
|
||
break;
|
||
case 6:
|
||
System.out.println("Saturday");
|
||
break;
|
||
case 7:
|
||
System.out.println("Sunday");
|
||
break;
|
||
default:
|
||
System.out.println("No Else");
|
||
break;
|
||
}
|
||
```
|
||
|
||
## 循环语句
|
||
|
||
### while 循环语句
|
||
|
||
```java
|
||
while(布尔值){
|
||
表达式
|
||
}
|
||
```
|
||
|
||
### do...while 循环语句
|
||
|
||
while 与 do...while 循环的唯一区别是 do...while 语句最少执行一次。
|
||
|
||
```java
|
||
int b = 10;
|
||
do {
|
||
System.out.println("b== " + b);
|
||
b--;
|
||
} while(b == 1);
|
||
```
|
||
|
||
### for 循环语句
|
||
|
||
```java
|
||
for(初始化; 布尔表达式; 步进){}
|
||
```
|
||
|
||
每次迭代前会测试布尔表达式,如果获得的结果是 false,就会执行 for 语句后面的代码;每次循环结束,会按照步进的值执行下一次循环。
|
||
|
||
#### 逗号操作符
|
||
|
||
在 for 语句表达式初始化部分,可以使用一系列的逗号分隔的语句;通过逗号操作符,可以在 for 语句内定义多个变量。
|
||
|
||
```java
|
||
for(int i = 1; j = i + 10;i < 5;i++, j = j * 2){}
|
||
```
|
||
|
||
#### for-each 语句
|
||
|
||
for-each 语句是一种更加简介的、方便对数组和集合进行遍历的方法。
|
||
|
||
```java
|
||
int array[] = {7, 8, 9};
|
||
|
||
for (int arr : array) {
|
||
System.out.println(arr);
|
||
}
|
||
```
|
||
|
||
## 跳转语句
|
||
|
||
### break 语句
|
||
|
||
终止循环
|
||
|
||
### continue 语句
|
||
|
||
跳出当前循环、执行下次循环。
|
||
|
||
### return 语句
|
||
|
||
返回语句
|