即控制程序的执行流程
1.分类
顺序结构、选择结构、循环结构
1.1.选择结构语句
- 分类
if 语句 、switch 语句 - if 语句示例
键盘录入x的值,求出y的值
x >=3 ;y = 2 * x + 1
-1 < x < 3 ;y = 2 * x
x <= -1 ;y = 2 * x - 1
Scanner sc = new Scanner(System.in);
System.out.println("输入x的值:");
int x = sc.nextInt();
int y = 0;
if(x >= 3){
y = 2 * x + 2;
}else if(x > -1 & x < 3){
y = 2 * x;
}else if(x <= -1){
y = 2 * x - 1;
}
System.out.println(y);
- switch 语句 注意事项
case 后只能是常量,不能是变量,且多个case后不能跟相同的值
default可放在任意位置,不影响运行顺序,且只在最后执行
1.2.循环结构 for 语句
- for 语句执行后变量会被释放,不能再使用
例:统计水仙花数有多少个
水仙花数:一个三位数,其各位数字的立方和等于该数本身
int count = 0;
for(int i = 100;i <= 999;i ++){
int ge = i % 10;
int shi = i / 10 % 10;
int bai = i / 100 % 10;
if(i == ge * ge * ge + shi * shi * shi + bai * bai * bai ){
count ++;
}
}
System.out.print(count); // 4(153、370、371、407)
1.3.循环结构 while语句
- 执行后,变量还可以继续使用
// 输出 1 - 10
int a = 1;
while (a <= 10){
System.out.println(a);
a ++;
}
1.4.循环结构 do…while语句
// 输出 1 - 10
int a = 1;
do {
System.out.println("a = " + a);
a++;
}while (a <= 10);
1.5.三种循环结构的区别
- do…while 至少执行一次循环体
- for 、while 必先判断条件是否成立,然后决定是否执行
int a = 11;
do {
System.out.println("a = " + a);
a++;
}while (a <= 10); // a = 11
int a = 11;
while(a <= 10){
System.out.println("a = " + a);
a ++;
} //无输出
- 想在循环结束后继续使用变量,用 while,否则使用 for 。如无法确定,推荐使用 for ,因为变量及早的从内存中消失,可提高内存使用效率
1.6.无限循环
- 无区别
while(true){
System.out.println("Hello world");
}
for(;;){
System.out.println("Hello world");
}
1.7.控制跳转语句
- break 使用在switch 和循环中,意为跳出循环
- continue 使用在循环中,意为终止本次循环继续下次循环
- return 结束方法