MacOs-JAVA开发6-流程控制语句
顺序语句
从上往下的执行 按照顺序,默认就是顺序语句
If语句
单分支if
语句格式:
if(条件表达式){
语句块
}
首先执行条件表达式,如果表达式为真,执行语句块;为否,不执行语句块。执行下一条语句。
public class Study {
public static void main(String[] args) {
System.out.println("程序开始");
int a = 10;
int b = 20;
if(a==b){
System.out.println("a等于b");
}
int c = 10;
if(a==c){
System.out.println("a等于c");
}
System.out.println("程序结束");
//注意事项:if语句体{}大括号里面如果只有一条语句,大括号是省略不写,但是不建议此写法!!
if(b==c)
System.out.println("b等于c");
}
}
双分支if
if(关系表达式){
语句体1
}else{
语句体2
}
如果条件表达式返回true,执行代码块1
如果条件表达式返回false,执行代码块2
if(age>=18) {
System.out.println("装环境");
System.out.println("写代码");
}else {
System.out.println("去黑网吧装环境");
System.out.println("写代码");
}
多分支if
if(判断段条件1){
语句体1;
}else if(判断段条件2){
语句体2;
}
…
else if(判断段条件n){
语句体n;
}else{
语句体n+1;
}
else分支:前面的所有的不成立,就会执行else分支的语句体
/*
* x和y的关系满足如下:
* x>=3 y=2x+1
* -1<=x<3 y=2x
* x<-1 y=2x-1
*/
int x = 5;
int y = 0;//局部变量
if(x>=3){
y = 2*x+1;
}else if(x>=-1&&x<3){
y = 2*x;
}else{
y = 2*x-1;
}
System.out.println("y的值为:"+y);
if嵌套
if可以嵌套 还可以无限嵌套
层级越多 阅读性越差
最多不超过三级 最好不要超过2级 最最好用一级
int a=25;
boolean isFriend=true;
if(a>18) {//25>18 true
System.out.println("满了18岁");
if(a>=22) {//25>22 true
System.out.println("可以結婚");
if(isFriend==true) {//true
System.out.println("結婚了");
}else {
System.out.println("上網......");
}
}else {
System.out.println("不可以");
}
}else {
System.out.println("没有");
}
switch语句
语句格式:
/* switch(算数表达式)
case 常量表达式1 :
语句块1
break;
case 常量表达式2 :
语句块2
break;
case 常量表达式3 :
语句块3
break;
*/
switch(a){
case 1:
System.out.println("1");
break
case 2:
System.out.println("2");
//如果匹配上了相應的case,後面的case不會進行匹配,會直接執行後面的代碼
break
case 3:
System.out.println("3");
break
defalut:
System.out.println("4")
}
//1.switch不支持long类型
//2.case常量不能超出范围
//swicth 支持byte short int char
//switch后面的case必须是同一种数据类型