JAVA Foundation (day 7) nested for loop while do while

Keywords: Java R Language

1 nested for loop

1.1 general

There are at least two for loops. Judge whether the inner layer can be executed according to the conditions of the outer layer
If it can be executed, loop the inner layer code, and then continue to judge whether to execute the next loop of the outer layer loop

1.2 nested for m

 

1.3 exercise: nested for loop introduction case


Create package: cn.tedu.basic
Create class: TestForDemo.java
Summary 1: the external loop is executed once and the internal loop is executed many times
Summary 2: outer loop control row, inner loop control column

package cn.tedu.basic;
/*This class is used to test nested for loops*/
public class TestForDemo {
    public static void main(String[] args) {
        //Execution sequence
        //Execute the first round of the outer loop, i=1, print 1, encounter the inner loop, print 12345, and I automatically increases to 2
        //Execute the second round of outer loop, i=2, print 2, encounter inner loop, print 12345, and I automatically increases to 3
        //Execute the third round of outer loop, i=3, print 3, encounter inner loop, print 12345, and I automatically increases to 4
        //If i is 4 and the cycle conditions are not met, the cycle ends
        /**Summary: the outer loop is executed once (control the number of rounds)
         * The inner loop is executed multiple times (the number of times in each round)*/
        for(int i = 1; i<=3;i++) {//Outer circulation
            System.out.println("Second of the outer cycle:"+i+"round");
            for(int j = 1; j <=5 ; j++) {//inner loop 
                System.out.println("The second stage of inner circulation"+j+"second");
            }
        }
        System.out.println("**************Print rectangle******************");
        //Perform sequence analysis:
        //In the first round of the outer layer, i=1, in case of an inner layer cycle, print * * * * *, the inner layer cycle ends, line feed, and i automatically increases to 2
        //In the second round of outer layer, i=2, in case of inner layer cycle, print * * * * *, the inner layer cycle ends, line feed, and i automatically increases to 3
        //In the third round of outer layer, i=3, in case of inner layer cycle, print * * * * *, the inner layer cycle ends, line feed, and i automatically increases to 4
        //At this time, the value of i is 4, which does not meet the cycle conditions, and the cycle ends
        /**Summary: the outer loop controls the number of rows
         * The inner loop controls the number of columns printed per row*/
        for(int i = 1;i<=3;i++) {
            for(int j = 1;j<=5;j++) {
                System.out.print("*");
            }
            System.out.println();//Wrap with blank lines
        }
    }
}

1.4 exercise: print left right triangle


Create package: cn.tedu.basic
Create class: testfortriangle. Java

package cn.tedu.basic;
/**Requirements: use the for loop to print the left right triangle*/
//Line 1 star 1*
//Line 2 star 2 **
//Row 3 star 3 * **
//Row 4 stars 4 * * **
//Row i star i * * **
public class TestForTriangle {
    public static void main(String[] args) {
        for(int i = 1;i<6;i++) {//External circulation
            for (int j = 1; j <=i; j++) {//Internal circulation
                //Note: the loop condition of the inner loop needs to be modified so that the maximum value of j changes with i, otherwise it will be written dead
                System.out.print("*");//Print on the same round / line without line break
            }
            System.out.println();//Blank lines are used to wrap lines
        }
    }
}

Exercise 1.5: print 99 multiplication table
Create package: cn.tedu.basic
Create class: TestFor99Excel.java

package cn.tedu.basic;
/**This class is used to test the completion of 99 multiplication tables*/
//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++) {//Control the number of lines and print 9 lines
            for (int j = 1; j <= i; j++) {//Control the number of columns, i rows print i columns
                //System.out.println("*");-- Print left right triangle
                //System.out.println("2*3=6");2--i 3--j 6--i*j
                //Splicing print formula, followed by a "\ T" indicates that this is a table format, \ t also known as tab
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
            }
            System.out.println();//Blank lines are used to wrap lines
        }
    }
}

2 break and continue


2.1 concept


break: directly end the current loop, jump out of the loop body, simple and rough

Statements in the loop body after break will not continue to be executed, and statements outside the loop will be executed
Note that if a nested for loop encounters a break in the inner loop, it will only jump out of the current inner loop

Continue: jump out of this cycle and continue to the next cycle

After continue, the statements in the body of the current cycle will not continue to be executed, but the next cycle will continue to be executed, and the statements outside the cycle will also be executed
 

 

 

2.2 exercise: Test Break and Continue


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

package cn.tedu.method;

import java.util.Scanner;

/**Demand: find the number 88
 * Prompt and accept the user to input the number 100 times. If it is not 88, continue to input, and find 88 to end*/
public class TestBreakAndContinue {
    public static void main(String[] args) {
        //The loop body can help us perform repetitive things and control the execution of the for loop 100 times
        for(int i = 1;i <= 100; i++) {
            //In each cycle, the number entered by the user shall be prompted and received
            System.out.println("please enter a number:");
            int input = new Scanner(System.in).nextInt();
            if(input != 88) {//The user did not enter 88
                continue;//Continue input directly
                /**Note that whether you add continue or not, you can continue to enter when you guess wrong
                 * It's just that with continue, the efficiency is higher. As long as the data is not equal to 88, there is no need to execute the following code
                 * Just guess the numbers in the next round* */
            /**break Or no code is allowed to be written after continue, which is unreachable code*/
            //System.out.println(0);//Unreachable code
            }
            System.out.println("I used it to test continue Did you skip the second half of the loop");
            if(input == 88) {//Found 88
                System.out.println("Congratulations,You guessed right!");
                break;//End program
                //System.out.println(0);//Unreachable code
            }
        }
    }
}

3 cycle structure 2: while

3.1 form (judgment before execution)

 

3.2 exercise: while exercise of guessing numbers


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

package cn.tedu.method;
 
import java.util.Random;
import java.util.Scanner;
 
/**
 * This class is used to practice while loops
 * Requirement: generate a random number and compare it with the number the user has been inputting until the user guesses it correctly
 * */
public class TestWhile {
    public static void main(String[] args) {
        int r = createNum();//Call a method that can generate a random number and receive the generated random number
        System.out.println("Make a note:"+r);
       
        //Call number guessing method 1--while
        guessNum(r); 
    } 
    //Create a way to guess numbers
    public static void guessNum(int r) {
        //1. Write an endless loop
        while(true) {//Dead loop -- the exit of the program needs to be set
            //2. Receive the value entered by the user
            System.out.println("Guess what~");
            int input = new Scanner(System.in).nextInt();
            //3. Judge whether the guess is correct (compare the number guessed by the user with the generated random number)
            if(input > r) {
                System.out.println("Guess big,Keep guessing");
            }else if(input < r) {
                System.out.println("Guess it's small,keep trying");
            }else if(input == r) {
                System.out.println("You guessed right!");
                //Be sure to note: set the program exit!!!
                break;
            }
        }
    }
 
    //Create a method to generate random numbers
    public static int createNum() {
        //Let the program generate a random number
        //java.util.Random, pay attention to the package guide, shortcut: Ctrl+Shift+O
        int random = new Random().nextInt(100);//Parameter 100 is user-defined, and the generated random number range is an integer of [0100]
        return random;
    }
}

4 cycle structure 3: do while

4.1 form (execute first and then judge, and the loop body code shall be executed at least once)

4.2 do while exercise

private static void f2() {
        int n;
        do {
            System.out.println("I am a circulatory body");
            n = new Random().nextInt(300);//Range of generated random numbers [0300)
            System.out.println(n);
        }while(n>100);
    }

5 expansion


5.1 differences between the three cycles


for: know the number of cycles
while/do while: when the number of cycles is uncertain
while: judge first. If the rules are not met, the code will not be executed
do while: the code is executed at least once, and then judge whether it meets the rules and execute the code again
Loops can replace each other, but it is generally best to choose an appropriate loop structure to complete the code~
 

5.2 print right triangle

*
   **
  ***
 ****
*****
 
 
package day999;
public class a {
    public static void main(String[] args) {
        //Output 5 lines
        for(int i=1;i<=5;i++){
            //Space triangle
            for(int x=5;x>i;x--){
                System.out.print(" ");
            }
            //*No. triangle
            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) {
        //Print 5 lines
        for(int i=1;i<=5;i++){
            //Print inverted triangle of space
            for(int j=5;j>=i;j--){
                System.out.print(" ");
            }
           
            //Print positive triangle with * sign
            for(int k=1;k<=i*2-1;k++){
                System.out.print("*");
            }
           
            System.out.println();
        }
    }
}

Posted by Saviola on Sun, 07 Nov 2021 14:42:30 -0800