4. JAVA nested for loop while do-while

1 Nested for loops

1.1 概述
There are at least 2 layers of for loops. According to the conditions of the outer layer, it is judged whether the inner layer can be executed.
If it can be executed, after the inner layer code is cycled, continue to judge whether to execute the next cycle of the outer layer loop.

1.2 嵌套for形式

insert image description here

1.3 Exercise: Introductory case of nested for loops

Create package: cn.tedu.basic
Create class: TestForDemo.java
Summary 1: The outer loop is executed once, and the inner loop is executed multiple times.
Summary 2: The outer loop controls rows, and the inner loop controls columns

package cn.tedu.basic;
/*本类用于测试嵌套for循环*/
public class TestForDemo {
    
    
	public static void main(String[] args) {
    
    
		//执行顺序
		//执行外层循环第一轮,i=1,打印1,遇到内层循环,打印12345,i自增成2
		//执行外层循环第二轮,i=2,打印2,遇到内层循环,打印12345,i自增成3
		//执行外层循环第三轮,i=3,打印3,遇到内层循环,打印12345,i自增成4
		//i为4,不满足循环条件,循环结束
		/**总结:外层循环执行一次(控制轮数)
		 * 内层循环执行多次(在每一轮中执行的次数)*/
		for(int i = 1; i<=3;i++) {
    
    //外层循环
			System.out.println("外层循环的第:"+i+"轮");
			for(int j = 1; j <=5 ; j++) {
    
    //内层循环
				System.out.println("内层循环的第"+j+"次");
			}
		}
		System.out.println("**************打印矩形******************");
		//执行顺序分析:
		//外层第一轮i=1,遇到内层循环,打印*****,内层循环结束,换行,i自增成2
		//外层第二轮i=2,遇到内层循环,打印*****,内层循环结束,换行,i自增成3
		//外层第三轮i=3,遇到内层循环,打印*****,内层循环结束,换行,i自增成4
		//此时i的值为4,不符合循环条件,循环结束
		/**总结:外层循环控制的是行数
		 * 内层循环控制的是每行打印的列数*/
		for(int i = 1;i<=3;i++) {
    
    
			for(int j = 1;j<=5;j++) {
    
    
				System.out.print("*");
			}
			System.out.println();//用空白行来换行
		}
	}
}


1.4 Exercise: Printing a left right triangle

Create package: cn.tedu.basic
Create class: TestForTriangle .java

package cn.tedu.basic;
/**需求:利用for循环,打印左直角三角形*/
//行1星1 *
//行2星2 * *
//行3星3 * * *
//行4星4 * * * *
//行i星i * * * * *
public class TestForTriangle {
    
    
    public static void main(String[] args) {
    
    
        for(int i = 1;i<6;i++) {
    
    //外循环
            for (int j = 1; j <=i; j++) {
    
    //内循环
                //注意:需要修改内循环的循环条件,让j的最大值随着i改变,否则写死了
                System.out.print("*");//在同一轮/同一行打印不换行
            }
            System.out.println();//空白行用来换行
        }
    }
}

1.5 Exercise: Print 99 multiplication table

Create package: cn.tedu.basic
Create class: TestFor99Excel.java

package cn.tedu.basic;
/**本类用于测试完成99乘法表*/
//1*1=1	
//1*2=2	2*2=4	
//1*3=3	2*3=6	3*3=9	
//1*4=4	2*4=8	3*4=12	4*4=16	
//1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
//1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
//1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
//1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
//1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81	
public class TestFor99Excel {
    
    
    public static void main(String[] args) {
    
    
        for (int i = 1; i <= 9; i++) {
    
    //控制行数,打印9行
            for (int j = 1; j <= i; j++) {
    
    //控制列数,i行打印i列
                //System.out.println("*");--打印左直角三角形
                //System.out.println("2*3=6");2--i 3--j 6--i*j
            	//拼接打印算式,后面拼接一个"\t"表示这是表格格式,\t也被称作制表符
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
            }
            System.out.println();//空白行用来换行
        }
    }
}

2 break与continue

2.1 Concept
break: directly end the current loop, jump out of the loop body, simple and rude

The statement in the loop body after the break will not continue to execute, and the loop outside the loop will execute.
Note that if it is a nested for loop, if the inner loop encounters a break, it will only jump out of the current inner loop.

continue: Jump out of the current cycle and continue to the next cycle

After continue, the statements in the current loop body will not continue to execute, but will continue to execute the next round of loop, and the loop outside the loop will also execute

insert image description here

2.2 Exercise: Test Break and Continue

Create package: cn.tedu.basic
Create class: TestBreakAndContinue.java

package cn.tedu.method;

import java.util.Scanner;

/**需求:找数字88
 * 提示并接受用户输入100次数字,如果不是88,则继续输入,找到88就结束*/
public class TestBreakAndContinue {
    
    
	public static void main(String[] args) {
    
    
		//循环体可以帮助我们执行重复的事情,控制for循环执行100次
		for(int i = 1;i <= 100; i++) {
    
    
			//在每一次循环中都要提示并接收用户输入的数字
			System.out.println("请输入数字:");
			int input = new Scanner(System.in).nextInt();
			if(input != 88) {
    
    //用户输入的不是88
				continue;//直接继续输入
				/**注意,不管是不是加continue,都可以在猜不对的情况下继续输入
				 * 只不过加了continue后效率更高,只要数据不等于88,就无需执行后面的代码
				 * 直接进行下一轮的猜数字即可* */
			/**break或者continue之后都不允许写代码,都是不可到达的代码*/
			//System.out.println(0);//Unreachable code
			}
			System.out.println("我是用来测试continue有没有跳过循环后半部分代码的哦");
			if(input == 88) {
    
    //找到88了
				System.out.println("恭喜您,猜对了!");
				break;//结束程序
				//System.out.println(0);//Unreachable code
			}
		}
	}
}

3 loop structure 2: while

3.1 Form (judgment first, then execution)

insert image description here

3.2 Practice: while practice of guessing numbers

Create package: cn.tedu.basic
Create class: TestWhile.java

package cn.tedu.method;
 
import java.util.Random;
import java.util.Scanner;
 
/**
 * 本类用于练习while循环
 * 需求: 产生一个随机数,和用户一直在输入的数字做比较,直到用户猜对
 * */
public class TestWhile {
    
    
    public static void main(String[] args) {
    
    
        int r = createNum();//调用可以生成随机数的方法,并且接收生成的随机数
        System.out.println("打个小抄:"+r);
       
        //调用猜数字方法1--while
        guessNum(r); 
    } 
    //创建猜数字的方法
    public static void guessNum(int r) {
    
    
        //1.写一个死循环
        while(true) {
    
    //死循环--需要设置程序的出口
            //2.接收用户输入的值
            System.out.println("猜猜看~");
            int input = new Scanner(System.in).nextInt();
            //3.判断是否猜对(拿用户猜的数字与生成的随机数做比较)
            if(input > r) {
    
    
                System.out.println("猜大了,继续猜猜看");
            }else if(input < r) {
    
    
                System.out.println("猜小了,继续努力");
            }else if(input == r) {
    
    
                System.out.println("猜对了!");
                //一定注意:要设置程序出口!!!
                break;
            }
        }
    }
 
    //创建一个用来生成随机数的方法
    public static int createNum() {
    
    
        //让程序产生一个随机数
        //java.util.Random,注意导包,快捷键:Ctrl+Shift+O
        int random = new Random().nextInt(100);//参数100是自定义的,此时生成的随机数范围是[0,100)的整数
        return random;
    }
}

4 Loop structure 3: do-while

4.1 Form (execute first, then judge, the code of the loop body is guaranteed to be executed at least once)

insert image description here

4.2 do-while exercises


private static void f2() {
    
    
		int n;
		do {
    
    
			System.out.println("我是循环体");
			n = new Random().nextInt(300);//生成随机数的范围[0,300)
			System.out.println(n);
		}while(n>100);
	}

5 expansion

5.1 The difference between the three loops
for: know the number of loops
while/do while: when the number of loops is uncertain
while: judge first, if it does not conform to the rules, do not execute the code
do while: the code is executed at least once, then judge, conform to the rules, Execute the code again.
The loops can replace each other, but it is generally best to choose the appropriate loop structure to complete the code~

5.2 Print right triangle

    *
   **
  ***
 ****
*****
 
 
package day999;
public class a {
    
    
    public static void main(String[] args) {
    
    
        //输出5行
        for(int i=1;i<=5;i++){
    
    
            //空格三角
            for(int x=5;x>i;x--){
    
    
                System.out.print(" ");
            }
            //*号三角
            for(int j=1;j<=i;j++){
    
    
                System.out.print("*");
            }
            System.out.println();
        }
    }
}


5.3 Printing full triangles

     *
    ***
   *****
  *******
**********
package day999;
public class a {
    
    
    public static void main(String[] args) {
    
    
        //打印5行
        for(int i=1;i<=5;i++){
    
    
            //打印空格的倒三角
            for(int j=5;j>=i;j--){
    
    
                System.out.print(" ");
            }
           
            //打印*号的正三角
            for(int k=1;k<=i*2-1;k++){
    
    
                System.out.print("*");
            }
           
            System.out.println();
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_58276266/article/details/131475708