2.循环方法

while循环

  1. while是最基本循环,结构为:

​ while(布尔表达式){

​ 循环内容

​ }

2.只要布尔表达式为true,循环会一直执行下去

  1. 大多数情况下会让循环停止下去我们需要一个表示式失效的方式来结束循环。
public class whileDemon01 {
	public static void main(String args[]) {
	    //输出100
		int i=0;
		while(i<100) {
			i++;
			System.out.println(i);
		}
	}

}

1 2 3 4 5......100
 ==========================================================================================================
    public class WhileDemon03 {
	public static void main(String args[]) {
		int i=0;
		int sum=0;
		while(i<100) {
			sum=sum+i;
			i++;
			//System.out.println(sum);当前累加项的和
		}
		System.out.println("sum:"+sum);
	}

}
sum:4950		

do…while循环

  1. do…whie 和while相似,不同的是,do…while循环至少循环一次。

​ do{

​ //代码语句

​ }while(布尔表达式);

2.While和do…While 的区别

  • while先执行后判断。dowhile是先执行后判断!

  • Do…while总是保证循环体会被至少执行一次!

    public class DoWhIileDemon04 {
    	public static void main(String args[]) {
    		int a=1;
    		while(a<2) {
    			System.out.println(a);
    			a++;
    		}
    		
    	System.out.println("================================");
    	do {
    		System.out.println(a);
    		a++;
    	}while(a<2);
     }
    
    }
    
    
    1
    ================================
    2
    
    

For循环

1.语法格式

for(初始化;布尔表达式;更新){

//代码语句

}

2.for循环语句是支持迭代的一种通用结构,是最有效,最灵活的循环结构。

public class ForDemon01 {
	public static void main(String args[]) {
		int a=1;//初始化条件		
	while(a<10) {//条件判断
			System.out.println(a);//循环体
			a+=2;//a=a+2也是迭代
		}
			System.out.println("while循环结束!:");
    }
}
1
3
5
7
9
while循环结束!:
添加for循环
public class ForDemon01 {
	public static void main(String args[]) {
		int a=1;//初始化条件
		  int i=1;
	while(a<10) {//条件判断
			System.out.println(a);//循环体
			a+=2;//a=a+2也是迭代
    }
			System.out.println("while循环结束!:");	
			  for(i=1;i<10;i++) {
				  System.out.println(i);
			  }
			  System.out.println("for循环结束");
	}
}

1
2
3
4
5
6
7
8
9
for循环结束

练习题

public class ForDemon02 {
	public static void main(String args[]) {
		//练习1:计算0到100之间偶数与奇数的和
		
		int oddSum=0;
		int evenSum=0;
		for(int i=0;i<=100;i++) {
			
			if(i%2!=0) {
				oddSum=oddSum+i;
			}
			else {
				evenSum+=i;
			}
			
		}
		System.out.println("奇数的和:"+oddSum);
		System.out.println("偶数的和:"+evenSum);
	}

}
奇数的和:2500
偶数的和:2550

public class ForDemon03 {
	public static void main(String args[]) {
		//练习2:循环输出1000之间能被5整除的数。而且每三个换行
		
		int i=0;
		for(i=0;i<=100;i++) {
			if(i%5==0) {
			System.out.print(i+"\t");	
			}
			if(i%(5*3)==0) {//每行
				//System.out.println();
				System.out.print("\n");
			}
		}
	}	
}
//println 输出完会换行
//print 输出完全不会换行   

0	
5	10	15	
20	25	30	
35	40	45	
50	55	60	
65	70	75	
80	85	90	
95	100	
    
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值