CGB Fifth Day

Posted by Benny Johnson on Wed, 08 Dec 2021 10:12:11 +0100

while Loop

Syntax Format: Loop Initial Value;

                  While {loop body;   Step statement;}

Execution process: first judge the Boolean expression, when the Boolean expression is true, execute the loop body and step statement, and then judge the Boolean expression again after execution, until the Boolean expression is false, stop the loop.

Scenario: while is often used for dead loops where the loop condition is written directly as true.

Guess Number Cases:

import java.util.Random;
import java.util.Scanner;

/**
 * This class is used for while loops
 */
public class WhileLoop {

    /**
     * Computer Generation of Random Numbers
     *
     * @return Return the computer to generate a random integer between 0 and 100 to the caller
     */
    public static int createNum() {

        Random random = new Random();

        return random.nextInt(101);
    }

    /**
     * How users enter guessed numbers
     *
     * @return Returns a user guessed number to the caller
     */
    public static int userGuess() {

        System.out.print("Please enter a 0-100 Integer:");

        Scanner sc = new Scanner(System.in);

        return sc.nextInt();
    }

    /**
     * Method of comparing user guessed numbers with computer randomly generated random numbers
     */
    public static void guess() {

        int computerNum = createNum();

        int playNum = userGuess();

        /**
         * while Commonly used for dead loops, where the loop condition is written directly as true
         * Dead cycle must set exit at appropriate time
         */
        while (true) {

            if (playNum == computerNum) {

                System.out.println("That's a terrific guess!!!");

                break;

            } else if (playNum > computerNum) {

                System.out.println("Unfortunately, you guessed it");

            } else {

                System.out.println("Unfortunately, the guess was too small");
            }

            playNum = userGuess();
        }
    }

    public static void main(String[] args) {

        /**
         * Requirements: Generate a random number and compare it with the number the user guessed until it is used to guess the right one
         */
        System.out.println("Let's play a little number guessing game!");

        guess();
    }
}

[Attention]

The while loop may not execute at one time.

You cannot add a semicolon after the while loop parentheses, otherwise it will become an infinite loop.

do-while Loop

Grammar Format:

do{

        Circulating body;

        } While (Boolean expression);

Execution process: the loop body is executed first, the Boolean expression is evaluated after the loop body is run, and the loop body continues to execute for true until the Boolean expression is false.

[Attention]

        do-while loops are executed at least once.

        The semicolon after the while parenthesis of do-while cannot be lost.

 int n = 0;

        int count = 0; // Count loops

        do {

            System.out.println("I am the circulatory body");

            n = new Random().nextInt(301);

            System.out.println("variable n The value of" + n);

            System.out.println();

            count++;

        }while (n != 250);

array

Array creation

Arrays are reference type variables that Java opens up continuous space in memory.

Arrays are created in two ways: dynamic and static.

Each subscript element in the array is assigned a value when the array is created statically.

        Static arrays are created in two ways:

              The first way is to create a static array: array type []array name= new array type []{value of array subscript element}

              The second way is to create a static array: array type [] array name = {value of the table element below the array}

Dynamic creation simply begins by specifying the length of the array, and the data for the array subscript elements is the system default.

        Create arrays dynamically: array type [] array name = new array type [array length];

        // 1. First way to create arrays statically
        int[] arrA = new int[]{1, 2, 3, 4};

        // 2. Second way to create arrays statically
        char[] ch = new char[]{'H', 'e', 'l', 'l', 'o'};

        // 3. Create arrays dynamically
        String[] arrStr = new String[3];

The length of the array  

Syntax for finding the length of an array: array name.length;

            // Statically Create Array
            int[] arrIntStaticOne = {1, 2, 3, 4, 5, 6};

            // Length of Print Output Array
            System.out.println(arrIntStaticOne.length);  // The length of the array is 6

[Attention]

        Once an array is created, the length of the array cannot be changed.

Subscript of array

Subscripts of arrays: Subscripts of arrays start at 0, and the maximum array subscript is the length of the array - 1.

We manipulate the values of the array subscript elements by manipulating the array subscript.

Arrays.toString() method

Print the output array name directly using the output statement to get the address value of the array in memory space.

Using Arrays.toString (parameter list); The method is used in conjunction with the output statement to obtain the data values of the following table elements of the array.

            // Statically Create Array
            int[] arrIntStaticOne = {1, 2, 3, 4, 5, 6};

            // Print out values in array subscript elements
            System.out.println(Arrays.toString(arrIntStaticOne));
            
            // The printout results are: [1, 2, 3, 4, 5, 6]

Arrays.toString (parameter list);

The parameter list is the name of the array that needs to be passed in.

[Attention]

         The Arrays tool class requires an import package.

        Char type arrays can be used directly with output statements to directly output the data values of the char type array subscript elements.

Expansion and contraction of arrays

The expansion and scaling of arrays requires copyOf (parameter list) in the Arrays tool class; Method

CopyOf (parameter list);

Parameter List 1: Arrays that need to be expanded

Parameter List 2: Length of Array

Expansion: Expand the capacity of an array. The length of the new array is longer than the length of the original array.

Expansion idea: first create a new array corresponding to the new length, each location has a default value of 0, and then copy the array from the original array to the new array, which is not overwritten or the default value.

Compact: Reduce the capacity of the array, and the length of the new array is less than the length of the array before it is condensed.

The idea for scaling up is to first create a new array corresponding to the new length, initialize a default value of 0 for each location, and then copy the specified number of data from the original array into the new array, similar to the "intercept" part.

Specifies that elements in the original array are truncated at the beginning and end:

copyOfRange(); Used to complete interception of arrays.
Parameter 1: Which array to truncate.
Parameter 2: From which subscript to start.
Parameter 3: To which subscript to end.
Interception range: left closed right open interval.
If the subscript crosses the boundary, it will intercept and expand.

[Attention]

The expansion and contraction of an array is not really expansion and contraction, because once the length of the array is created it cannot be changed. Instead, it creates a new array in memory, replacing the address value of the original array stored by the array variable name with the address value of the new array, and the original array will be disposed of by the Java recycling mechanism.

Loop through the contents of the output array

    /**
     * Create a method to get the number of days per month for 12 months in a year and print out
     */
    public static void dayOfMonth() {

        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        for (int i = 0; i < days.length; i++) {

            System.out.println("No." + (i + 1) + "Months are:" + days[i] + "day");
        }
    }

i   < Days.length; The reason is that since the array subscript starts, the maximum value of the array subscript is equal to the length of the array-1.

If equal to the length of the array, an array subscript crossing exception occurs. Each value of i represents each subscript of the days array.

Method

Method overload:

Meaning of overloading methods: to improve code reuse and flexibility.

Method overload:
     In the same class, there are methods with the same method name but different parameter lists
     If the number of parameters of a method with the same name is different in the same class, it must constitute an overload
     If the number of parameters of a method with the same name is different in the same class, it may constitute an overload and you need to look at the parameter type of the method, regardless of the parameter name.

[Attention]
     Method overload is related to the parameter type of the method
     Method overload is independent of method parameter name
     Method overload is independent of method return value
     Method overload is related to the name of the method
     Method overload is not related to method access modifiers
     Method overload is related to the number of parameter lists of the method

/**
 * Overload of this class for demonstrating methods
 */
public class MethodOverride {

    private static void method() {

        System.out.println("Ha Ha Ha Ha Ha Ha, I don't have parameters and return values");
    }

    public static void method(int num){

        System.out.println("Hahaha, my parameter is" + num);
    }

    public static void main(String[] args) {

        /**
         * Invoke method by method name + parameter list
         *
         * Method overload:
         * In the same class, there are methods with the same method name but different parameter lists
         *
         * If the number of parameters of a method with the same name is different in the same class, it must constitute an overload
         * If the number of parameters of a method with the same name is different in the same class, it may constitute an overload and you need to look at the parameter type of the method, regardless of the parameter name.
         *
         * Method overload is related to the parameter type of the method
         * Method overload is independent of method parameter name
         * Method overload is independent of method return value
         * Method overload is related to the name of the method
         * Method overload is not related to method access modifiers
         * Method overload is related to the number of parameter lists of the method
         */
        method();

        method(666);
    }


}

Topics: WPF linq p2p