流程控制

流程控制

本节基本内容

在这里插入图片描述

1.选择结构:

1if:单分支、双分支、多分支

2switch:表达式的值不能是longfloatdouble、boolea类型、default的位置随意但一般放最后。

3)注意:
  当if分支中存在单条语句时可以省略大括号。 
  当整个if的表达式无论真假,执行之后都会执行后续代码 
  以后多大数的逻辑不单单只有两种情况,有待加强。 
  单分支结构永远只能保证一种情况下会做什么操作。
  switch只能用于等值判定、而if可以做区间判定
if:
//for循环
public class Loop01{
	public static void main(String[] args){
		if(67>56){
			System.out.println("该循环体被执行了");
		}
		
		if(67<56){
			System.out.println("这是对的");	
		}else{
			System.out.println("这是错的");
		}
		
		int score=(int)(Math.random()*99);
		System.out.println(score);
		if(score>=90){
			System.out.println("优秀");	
		}else if(score>=80){
			System.out.println("良好");
		}else if(score>=70){
			System.out.println("中等");
		}else if(score>=60){
			System.out.println("及格");
		}else{
			System.out.println("菜鸡");
		}
	}
}

执行结果:

在这里插入图片描述

switch:
public class Loop{
	public static void main(String[] args){
		int month=(int)(Math.random()*12+1);
		System.out.println("当前月份数为"+month);
		switch(month){
			case 1:
			case 11:
			case 12:
			System.out.println("冬天");
			break;
			case 2:
			case 3:
			case 4:
			System.out.println("春天");
			break;
			case 5:
			case 6:
			case 7:
			System.out.println("夏天");
			break;
			case 8:
			case 9:
			case 10:
			System.out.println("冬天");
			break;	
		}
	}
}

执行结果:

在这里插入图片描述

2.循环结构:

1while:不确定循环次数可以优先考虑while循环

2do-while3for:确定循环次数可以使用for循环

4)注意:while先判定再执行

       do-while先执行再判定
while:

public class Loop03{
	public static void main(String[] args){
		int a=0;
		while(a<5){
			System.out.println("a的值是"+a);
			a++;
		}
	}	
}
执行结果

在这里插入图片描述

do-while:

public class Loop04{
	public static void main(String[] args){
		int a=0;
		do{
			System.out.println("a的值是"+a);
			a++;
		}while(a<5);
	}	
}
执行结果:

[外链图片转存失败(img-T3tV70kI-1562859307602)(C:\Users\盛萌\AppData\Roaming\Typora\typora-user-images\1562858373366.png)]

while与do-while的区别:

 1while先判定再执行

 2do-while先执行再判定

public class Loop03{
	public static void main(String[] args){
		int a=0;
		while(a<0){
			System.out.println("a的值是"+a);
			a++;
		}
	}	
}
执行结果:
while循环时不满足条件不会执行循环体。

在这里插入图片描述

public class Loop04{
	public static void main(String[] args){
		int a=0;
		do{
			System.out.println("a的值是"+a);
			a++;
		}while(a<0);
	}	
}
执行结果:
do-while循环先执行一次再判断条件

在这里插入图片描述

for:

public class Loop02{
	public static void main(String[] args){
		//int count=0;
		for(int i=1,count=0;i<=100;i++){
			if(i%5==0){
				System.out.print(i+"\t");
				count++;
				if(count%3==0){
					System.out.print("\n");
				}
				
			}else{
				continue;
			}
		}
		
	}
}
执行结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值