控制流程
一、条件语句
条件语句可根据不同的条件执行不同的语句。
1.1 if条件语句
使用if条件语句,可选择是否要执行紧跟在条件之后的那个语句。关键字if之后是作为条件的“布尔表达式”,如果该表达式返回true,则执行其后的语句;若为false,则不执行if后的语句。
int a = 1;
if(a == 1) {
System.out.println(a);
}
1.2 if···else语句
public class Getifelse {
2
3 public static void main(String[] args) {
4 int math = 80; // 声明,数学成绩为80(及格)
5 int english = 50; // 声明,英语成绩为50(不及格)
6
7 if(math >= 60) { // if判断语句判断math是否大于等于60
8 System.out.println("math has passed");
9 } else { // if条件不成立
10 System.out.println("math has not passed");
11 }
12
13 if(english >= 60) { // if判断语句判断english是否大于等于60
14 System.out.println("english has passed");
15 } else { // if条件不成立
16 System.out.println("english has not passed");
17 }
18 }
19
20 }
1.3 if···else if多分支语句
1 public class GetTerm {
2
3 public static void main(String[] args) {
4 int x = 40;
5
6 if(x > 60) {
7 System.out.println("x的值大于60");
8 } else if (x > 30) {
9 System.out.println("x的值大于30但小于60");
10 } else if (x > 0) {
11 System.out.println("x的值大于0但小于30");
12 } else {
13 System.out.println("x的值小于等于0");
14 }
15 }
16
17 }
1.4 switch多分支语句
1 import java.util.Scanner;
2
3 public class GetSwitch {
4
5 public static void main(String[] args) {
6 Scanner scan = new Scanner(System.in);
7 System.out.print("请输入今天星期几:");
8 int week = scan.nextInt();
9
10 switch (week) {
11 case 1:
12 System.out.println("Monday");
13 break;
14 case 2:
15 System.out.println("Tuesday");
16 break;
17 case 3:
18 System.out.println("Wednesday");
19 break;
20 case 4:
21 System.out.println("Thursday");
22 break;
23 case 5:
24 System.out.println("Friday");
25 break;
26 case 6:
27 System.out.println("Saturday");
28 break;
29 case 7:
30 System.out.println("Sunday");
31 break;
32 default:
33 System.out.println("Sorry,I don't konw");
34 break;
35 }
36 }
37
38 }
二、循环语句
2.1 while循环语句
while循环语句的循环方式为利用一个条件来控制是否要继续反复执行这个语句。
1 public class GetSum {
2
3 public static void main(String[] args) {
4 int x = 1; // 定义初值
5 int sum = 0; // 定义求和变量,用于存储相加后的结果
6
7 while(x <= 10) {
8 sum += x; // 循环相加,也即 sum = sum + x;
9 x++;
10 }
11 System.out.println(sum);
12 }
13
14 }
2.2 do···while循环语句
1 public class Cycle {
2
3 public static void main(String[] args) {
4 int a = 10;
5 int b = 10;
6
7 // while循环语句
8 while(a == 8) {
9 System.out.println("a == " + a);
10 a--;
11 }
12
13 // do···while循环语句
14 do {
15 System.out.println("b == " + b);
16 b--;
17 } while(b == 8);
18 }
19
20 }
2.3 for循环语句
1 public class Circulate {
2
3 public static void main(String[] args) {
4 int sum = 0;
5
6 for(int i=2; i<=100; i+=2) {
7 sum += i;
8 }
9
10 System.out.println(sum);
11 }
12
13 }
三、跳转语句
Java语言提供了三种跳转语句,分别是break语句、continue语句和return语句。
3.1 break语句
for(int i=0; i<n; i++) { // 外层循环
for(int j=0; j<n ;j++) { // 内层循环
break;
}
}
3.2 continue语句
public class ContinueDemo {
2
3 public static void main(String[] args) {
4 int i = 0;
5
6 while(i < 10) {
7 i++;
8
9 if(i%2 == 0) { // 能被2整除,是偶数
10 continue; // 跳过当前循环
11 }
12
13 System.out.print(i + " ");
14 }
15 }
16
17 }
3.3 return语句
public void getName() {
return name;
}