流程控制语句

来源:互联网 发布:怎样鉴别mac口红真假 编辑:程序博客网 时间:2024/06/18 16:40
一 . 复合语句
复合语句是以整个块区为单位的语句,所以又称为块语句,复合语句由"{"开始,闭括号"}"结束
二 . 条件语句
if语句:语法: if(布尔表达式){ 语句序列 }
布尔表达式:必要参数,表示最后返回的结果必须是一个布尔值,可以是一个常量或者变量,也可以是使用关系或布尔运算符的表达式
语句序列:可选参数,可以是一条语句或者多条语句,当表达式的值为true时执行这些语句,若语句序列中仅有一条语句,则可以省略条件语句的'{ }'.


if...else语句
语法:
if(表达式){
若干语句
}else{
若干语句
}

if....else...可看做是三目运算符的另一个写法


if....else if () 语句
语法 if(条件表达式1){
语句序列1
}else if(条件表达式2){
语句序列2
}else if(条件表达式3){
语句序列3
}



switch语句
语法 switch(表达式)
{
case 常量1:
语句块1
[break;]
............
case 常量n:
语句块1
[break;]
default:
语句块 n+1;
[break]
}


while循环语句
语法:
while(条件表达式){
执行语句
}



do...while循环语句先执行一次循环,再判断条件是否成立
语法:
do{
执行语句
}
while(条件表达式);

for循环语句
语法:
for(表达式1 ;表达式2 ; 表达式3; ){
语句序列
}

break和continue都是用来控制循环结构的,主要是停止循环。
1.break
有时候我们想在某种条件出现的时候终止循环而不是等到循环条件为false才终止。
这是我们可以使用break来完成。break用于完全结束一个循环,跳出循环体执行循环后面的语句。
2.continue
continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环。
可以理解为continue是跳过当次循环中剩下的语句,执行下一次循环

闰年的判断实例(多个case的使用)
public class Date {public static void main(String[] args) {System.out.println("*******************************************");System.out.println("请输入年份:");Scanner sc = new Scanner(System.in);int year = sc.nextInt();if(  year % 4 ==0 && year % 100 != 0 || year % 400 == 0){System.out.println("请输入月份");int  month =sc.nextInt();switch(month){case 1:  case 3:  case 5: case 7: case 8: case 10: case 12: System.out.println(year+"年"+month+"月有31天");break;case 2:System.out.println(year+"年"+month+"月有29天");break;case 4: case 6: case 9: case 11:System.out.println(year+"年"+month+"月有30天");break;default:System.out.println("对不起您输入的有误");}}else{System.out.println("请输入月份");int  month =sc.nextInt();switch(month){case 1:  case 3:  case 5: case 7: case 8: case 10: case 12: System.out.println(year+"年"+month+"月有31天");break;case 2:System.out.println(year+"年"+month+"月有28天");break;case 4: case 6: case 9: case 11:System.out.println(year+"年"+month+"月有30天");break;default:System.out.println("对不起您输入的有误");}}System.out.println("*******************************************");sc.close();}}

原创粉丝点击