〔004〕Java basic arrays and methods

▷ Static initialization array

  • 数组: is a container used to store a batch of 同种类型 data
  • 静态化数组:It is to pre-fill the elements of the array and know what values ​​​​the array has.
  • 格式: definition 数据类型[] 数组名 can also be written as 数据类型 数组名[]
  • 注意:What type of array can only store what type of data?
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 定义整数类型的数组
        int[] arr = {
    
    1, 20, 32, 41, 54};

        // 定义字符串类型的数组
        String[] names = {
    
    "飞兔小哥", "博客专家", "天猫精灵测评官"};
    }
}

Static initialization array

▷ Three ways to statically initialize array definitions

  • method one: 数组类型[] 数组名 = new 数组类型{元素一, 元素二, 元素三}
  • Method two: 数组类型[] 数组名 = {元素一, 元素二, 元素三}
  • Method three: 数组类型 数组名[] = {元素一, 元素二, 元素三}
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 定义数组的方式一
        String[] names = new String[]{
    
    "飞兔小哥", "博客专家", "天猫精灵测评官"};

        // 定义数组的方式二
        int[] age = {
    
    20, 25, 32};

        // 定义数组的方式三
        double height[] = new double[]{
    
    172.4, 168.9, 184.9};
    }
}

Three ways to define arrays

▷ Array access

  • Format: 数组名[索引], where index starts from 0
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String[] names = new String[]{
    
    "飞兔小哥", "博客专家", "天猫精灵测评官"};
        System.out.println(names[0]);
        System.out.println(names[1]);
        System.out.println(names[2]);
    }
}

access array

▷The length of the array

  • Format: 数组名.length, through this program you can get the number of elements in the array
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String[] names = new String[]{
    
    "飞兔小哥", "博客专家", "天猫精灵测评官"};
        System.out.println(names.length);
    }
}

length of array

▷ Array storage principle

  • The array variable stores the array at 内存中的地址, and the array is a reference type of data, and the address of the variable points to the final data
  • Just like the array name is the house number, you can only find your home through the house number.

Storage principle

Storage principle

▷ Traversal of arrays

  • 遍历: Access the elements of the array one by one, which can be traversed through for loop
  • For example, if you don't know how many elements there are in the array, and you want to calculate the sum of the elements,
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int ages[] = {
    
    10, 20, 30, 40};
        int count = 0;

        for (int i = 0; i < ages.length; i++) {
    
    
            count += ages[i];
        }

        System.out.println(count);
    }
}

Array traversal

▷ Dynamic initialization of arrays

  • 动态化数组:That is, when defining an array, the specific values ​​of the elements are not stored, but only the data type stored in the array and the length of the array are determined.
  • Suitable for business scenarios where the specific element values ​​are uncertain at first and only the number of elements is known.
  • Format: 数据类型[] 数组名 = new 数据类型[长度]
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String[] names = new String[3];

        names[0] = "飞兔小哥";
        names[1] = "博客专家";
        names[2] = "天猫精灵测评官";

        System.out.println(names[0]);
        System.out.println(names[1]);
        System.out.println(names[2]);
    }
}

Dynamically initialize array

▷ Find the maximum value of an array

  • For example, given an array of integers, find the maximum value in it
  • It is to traverse the array, determine if each value is greater than the previous value, and assign the larger value to the variable.
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int age[] = {
    
    10, 20, 40, 30};
        int max = age[0]; // 定义最开始的值

        for (int i = 0; i < age.length; i++) {
    
    
            if (age[i] > max) max = age[i];
        }

        System.out.println("最大值为:" + max);
    }
}

Find the best value

▷ Array reversal

  • For example, given an integer array {10, 20, 40, 30}, reverse it into {30, 40, 20, 10}
  • The principle is to first swap the positions of the first element and the last element, then swap the second element and the penultimate element, and then keep going.
  • You can define two variablesi和j, where i the default value moves to the right from the first element, j By default, the last element moves to the left, and the positions of the two elements can be swapped every time

Array reversal

▷ debug tools

  • When writing a program, you can see that the editor has given you error prompts very intuitively.
  • But if you want to see the changes in values ​​during operation, you need to use the editor's debug tool
  • First, you need to set a breakpoint on 行号, then right-click and select debug to run, click the run button, and you can see it in the editor The changes in the array are very clear

debug tools

debug tools

▷ Method

  • 方法:It is a grammatical structure that encapsulates a piece of code into a function so that it can be called repeatedly
  • 方法It can improve the repeatability of code, improve development efficiency, and also make the logic of the program clearer.
  • Method definition format: 修饰词 返回值类型 方法名(形参列表) { 代码; return 返回值; }
  • Note: If the method declares a specific return value type, the internal return must return the corresponding data type
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int count = sum(1, 2);
        System.out.println(count);
    }

    public static int sum(int a, int b) {
    
    
        return a + b;
    }
}

▷ Return value

  • If the defined method does not return a value, then the type of the return value needs to be defined asvoid
  • If the defined method has a return value, the internal return must return the corresponding data type
  • There can be multiple formal parameter lists, or even none; if there are multiple formal parameters, they need to be separated by commas, and initialization values ​​cannot be given.
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    	// 有返回值的方法
        int count = sum(1, 2);
        System.out.println(count);
        
        // 直接调用无返回值的方法
        say();
    }

    public static void say() {
    
    
        System.out.println("我是飞兔小哥");
    }

    public static int sum(int a, int b) {
    
    
        return a + b;
    }
}

▷ Sum

  • Request 1到n的和 has a return value, that is, the final sum needs to be printed
  • From the primary school summation formula, we can know that the formula for finding the sum from 1 to n is:(1+n)*n/2
  • Because the final sum is an integer, the return type needs to be defined asint
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int count = sum(100);
        System.out.println(count);
    }

    public static int sum(int n) {
    
    
        return (1 + n) * n / 2;
    }
}

Sum

▷ Parity

  • To determine the parity of a number, you only need to print the result and do not need to return a value.
  • At this time, the type of the return value can be defined asvoid
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        judge(51);
        judge(60);
    }

    public static void judge(int number) {
    
    
        if (number % 2 == 0) {
    
    
            System.out.println(number + "是一个偶数");
        } else {
    
    
            System.out.println(number + "是一个奇数");
        }
    }
}

Parity

▷Parameter passing

  • 值传递:It means that when transferring actual parameters to formal parameters in a method, what is transferred is a copy of the value stored in the actual parameter variable. Modifying the value of the parameter in the copy will not change the value of the actual parameter.
  • 引用值传递:When transferring to a formal parameter, the address of the actual parameter is passed. After modifying the value, the value in the actual parameter will be changed. For example, an array is passed by reference.
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 值传递
        int a = 20;
        change(a);
        System.out.println(a);
    }

    public static void change(int a) {
    
    
        System.out.println(a);
        a = 520; // 修改值
        System.out.println(a);
    }
}

Pass by value

package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 引用值传递
        int a[] = {
    
    10, 20, 30};
        change(a);
        System.out.println(a[1]);
    }

    public static void change(int[] a) {
    
    
        System.out.println(a[1]);
        a[1] = 520; // 修改值
        System.out.println(a[1]);
    }
}

pass by reference

▷ Method overloading

  • 方法重载: is the 名称相同 of multiple methods in a class, but their 形参列表不同 does not matter other things, such as modifiers and return value types. wait.
  • 形参列表的不同:It refers to the different number, type and order of formal parameters, and does not care about the name of the formal parameters.
  • For example, create NPC in the game, and set the blood volume to NPC
package tiny.geeker;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(create("飞兔小哥"));
        System.out.println(create("飞兔小哥", 10000));
    }

    public static String create(String name) {
    
    
        return "创建了NPC:" + name;
    }

    public static String create(String name, int blood) {
    
    
        return "创建了NPC:" + name + ",血量为:" + blood;
    }
}

Method overloading

▷Case: Create verification code

  • Specify the program to generate a verification code of n digits, and then the program will randomly return a string of n digits
package tiny.geeker;

import java.util.Random;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String code = qrcode(5);
        System.out.println(code);
    }

    public static String qrcode(int n) {
    
    
        String code = "";
        Random r = new Random();

        for (int i = 0; i < n; i++) {
    
    
            int type = r.nextInt(3);
            switch (type) {
    
    
                case 0:
                    // 生成小数
                    code += r.nextInt(10);
                    break;
                case 1:
                    // 生成小写字母
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    // 生成大写字母
                    char ch2 = (char) (r.nextInt(26) + 65);
                    code += ch2;
                    break;
            }
        }
        return code;
    }
}

Create verification code

Guess you like

Origin blog.csdn.net/weixin_41635750/article/details/134380609