18 while循环和break等关键字

while循环

				while(条件){
				      //循环体
				}
public class TestWhile {
    public static void main(String[] args) {
        int i=0;
        while (i<100){
        System.out.println("hello"+(i+1));
		i++;
		}
    }
}

do while循环

   do {
         //循环体
   }  while(条件);
public class TestWhile {
    public static void main(String[] args) {
        double ji = 1;
		int i = 1;
		do{
			ji *=i;
			i++;
		} while (i<=100);
		System.out.println("1到100的乘积为:"+ji);
		
    }
}

死循环:条件永远满足,导致循环永远执行

while(true){
}

public class TestBreak{
   public static void main(String[] args) {
	  while (true) {
		  System.out.println("这是一个死循环");
		
	  }
	  
   }

} //ctrl+c结束死循环

for( ;true; ){
}

public class TestBreak{
   public static void main(String[] args) {
	  //while (true) {
	  //  System.out.println("这是一个死循环");
	// }
	  
 //ctrl+c结束死循环

        for( ;true; ){
        System.out.println("这是一个死循环");	
        }
   }
}

break和continue 关键字

break:终止循环
continue:跳过本次循环,执行下次循环

public class TestBreak{
   public static void main(String[] args) {
	   for (int i=0;i<100 ;++i ){
		   if (i==50){
			  // break;//break关键字可以终止switch语句和循环
			   continue;
		   }
		   System.out.println(i);
	   }
   }
}

在这里插入图片描述

课堂练习

1 打印直角三角形

import java.util.Scanner;
public class TestStar {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		System.out.print("请输入你要打印的层数:");
		int layer = in.nextInt();
		//外层的循环,是用来打印多少层数的
		for(int i = 1;i<=layer;++i){
			//打印*
			for (int j=1; j<=i;++j ){
				System.out.print("*");
			}
			System.out.println("");
		}
	}

}

在这里插入图片描述
2打印九九乘法表
2.1

public class TestJiuJiu {
	public static void main(String[] args){
		for(int i = 1;i<=9;++i){ //外层循环是用来输出行
			for (int j=1; j<=i;++j ){
				System.out.print(j+"*"+i+"="+(i*j)+"\t");//内层循环输出列
			}
			System.out.println("");
		}
	}

}

在这里插入图片描述
2.2

public class TestJiuJiu {
	public static void main(String[] args){
		for(int i = 1;i<=9;++i){ 
			for (int j=1; j<=i;++j ){
				int sum = i*j;
				if(sum>9){
					System.out.print(j+"*"+i+"="+(sum)+" ");
				} else
				    System.out.print(j+"*"+i+"="+(sum)+"  ");
			}
			System.out.println("");
		}

	}

}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值