java06 顺序结构 选择判断结构 与循环语句
1流程概述
程序运行过程,主要分为三类,顺序结构,判断结构与循环结构,它自程序入口后,执行一系列开发者的流程规划。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。2顺序结构
一以贯之:一条路走到底
public class Hello{ public static void main(String[] args){ System.out.println("中国"); System.out.println("爱好"); System.out.println("和平"); } } 结果: 中国 爱好 和平
3判断结构-选择结构 if语句(3种)和switch语句
3.1.if语句
if语句包含3种
1.单if语句
2.if 。。。else语句
3.if。。。elseif。。。。else 语句
3.1.1 单if语句
格式:
if(关系表达式){
语句体1;
}
流程图:
说明:单if语句含义是 if之后的条件表达式满足条件为true ,即执行语句体。否则不执行。
public class Hello{ public static void main(String[] args){ System.out.println("中国计划"); int num1 = 101; if(num1 >= 100) { System.out.println("打击美帝国霸权主义和日韩摇摆者"); } System.out.println("当然我们也爱好"); System.out.println("和平"); } } 结果: 中国计划 打击美帝国霸权主义和日韩走狗棒子 当然我们也爱好 和平
3.1.2 if。。。else语句
格式:
if(关系表达式){
语句体1;
}else{
语句体2;
}
流程
简单说,就是只选择一个语句体执行,二者选其一;
1 关系表达式为true ,执行语句体1;
2 关系表达式为false,执行语句体2;
public class hello { public static void main(String[] args) { int a = 33; //判断其是单数还是双数 if(a % 2 == 0) { System.out.println("是偶数"); }else { System.out.println("是奇数"); } } } 结果:奇数
3.1.3 if。。。 elseif。。。 else语句 (复合if扩展语句)
简单的说就是N中选一
public class hello { public static void main(String[] args) { int a = 33; int y; //根据a的大小,选择y的计算公式并输出结果 if(a >= 3) { y = 2 * a ; }else if (a < 3 && a > 1) { y = a - 1; }else { y = a; } System.out.println(y); } } 结果 66
使用三元运算符和if else语句进行实现。
public class hello { public static void main(String[] args) { int a = 10; int b = 20; int max; if (a > b) { max = a; }else { max = b; }System.out.println(max); } }
public class hello { public static void main(String[] args) { int a = 10; int b = 20; int max = a > b ? a:b; System.out.println(max); } }
3.3.4 Switch结构
语法结构
switch(表达式){ // 表达式的值最终与case 常量比较
case 常量1:
语句体1;
break; //遇到break结束
case 常量2:
语句体2;
break;
。。。
case 常量n:
语句体n;
break;
default: //default 作用是 收尾
语句体n+1;
break;//最后一个break可以省略,但不建议
}
说明:
1. n中选一,如果n中没有,执行default的n+1;
2. 任意一个执行到break结束。
public class hello { public static void main(String[] args) { int a = 1; switch (a) { case 1 : System.out.println("中国统一世界"); break; case 2 : System.out.println("美国认中国为大哥"); break; case 3 : System.out.println("美国邀请中国管理美国"); break;//不建议最后一个break删除 } } }
注意事项
1 switch中的多个case的常量值不可以重复,编译会报错;
2 switch后面小括号的值只能是四种基本数据类型 char short byte int和两种引用数据类型 string字符串和 enum枚举
3 switch 语句很灵活
4 循环结构
