The fifth day of Java basic learning (function, one-dimensional array, two-dimensional array)

1. Function (method)

1. The role of functions: Improve the reusability of function codes

2, the definition format of the function

    修饰符  返回值类型  函数名(形参列表){
        需要被封装的功能代码;
        return 结果;
    }
class Demo5.1{
    public static void main(String[] args){
        int sum = add(2,3); //调用了add名字的函数
        System.out.println("结果:"+ sum);
    }
    //做加法功能的函数
    public static int add(int a,int b){ // a、b 形式参数: 形式参数的值是交给调用者确定的
        return a+b;
    }
}   

① Modifier: public static.
② Return value type: int. The return value type refers to the data type of the result returned after the function runs.
Note: Some functions return no result to the caller, so the return value type is void.
③ Function name: add.
The role of the function name: The function name that needs to be used if the function needs to be called.
Naming conventions for function names: the first word is all lowercase, the first letter of other words is capitalized, and the other words are lowercase.
④ return: return a result to the caller.
⑤ Formal parameters: If there is data to be determined by the caller when a function is running, then formal parameters should be defined at this time.

3. After the function is defined, it needs to be called before it is executed. The main function is called by the jvm, and we do not need to call it manually.

4. How to define a function:
① Return value type.
② Whether there are unknown parameters (whether there are parameters to be determined by the caller)

class Demo5.2{
    public static void main(String[] args){
        int max = getMax(14,5); //调用了函数 实际参数
        System.out.println("最大值:"+ max);
    }
    //定义一个函数比较两个int类型的数据大小,把最大值返回给调用者
    public static int getMax(int a, int b){// 形式参数
        int max = 0; //定义一个变量用于保存最大值的
        if(a>b){
            max = a;
        }else{
            max = b;
        }
        return max; //把结果返回给调用者
    }
}

5. Requirement 1: Define a function to judge the grade of a score and return the grade of the score to the caller.
① Return value type: String
② Unknown parameter: Fraction
Requirement 2: Define a function to print a multiplication table without returning any data.
① Return value type: void
② Unknown parameter: multiplication table of a few times a few

class Demo5.3 {
    public static void main(String[] args){
        String result = getGrade(96);
        System.out.println(result);

        print(7);
    }
    //需求1: 定义一个函数判断一个分数的等级,把分数的等级返回给调用者。
    public static String getGrade(int score){
        String grade = "";  //定义一个变量存储等级
        if(score>=90&&score<=100){
            grade = "A等级";
        }else if(score>=80&&score<=89){
            grade = "B等级";
        }else if(score>=70&&score<=79){
            grade = "C等级";
        }else if(score>=60&&score<=69){
            grade = "D等级";
        }else if(score>=0&&score<=59){
            grade = "E等级";
        }else{
            grade = "补考";
        }
        return grade;//把等级返回给调用者
    }
    //需求2: 定义一个函数打印一个乘法表,不需要返回任何数据。 
    public static void  print(int row){
        for(int i = 1 ; i<= row ; i++){
            for (int j = 1 ;j<=i  ;j++ ){
                System.out.print(i+"*"+j+"="+i*j+"\t");
            }
            System.out.println();//换行
        }
    }   
}

6. Features of
the function ① The function of the function is to encapsulate a function code to improve the reusability of the function code.
② After the function is defined, it needs to be called before it is executed.
③ If a function does not return a value to the caller, the return value type must be represented by void.

7. Note
① If the return value type of a function is a specific data type, then the function must ensure that there is a return value in any case. (Except the return value type is void)
② If the return value type of a function is void, the return keyword can also appear, but there can be no data behind the return keyword.

8. Function overloading
① Function overloading: When two or more functions with the same name appear in a class, this is called function overloading.
② The function of function overloading: Different functions can appear with the same function name to deal with parameters of different numbers or data types.
③ Requirements for function overloading: the function name is the same; the formal parameter list is inconsistent (the number of formal parameters or the corresponding data type is inconsistent); it has nothing to do with the return value type of the function.

class Demo5.4{
    public static void main(String[] args){
        add(1,2);
        add(1,2.0);
    }
    // 这些函数都是在做加法运算
    public static double add(int a,int b){
        System.out.println("两个int参数的总和: "+ (a+b));
        return 3.14;
    }   
    public static int add(double a,double b){
        System.out.println("两个double参数的总和: "+ (a+b));
        return 12;
    }
    public static void add(int a,int b,int c){
        System.out.println("三个int参数的总和: "+ (a+b+c));
    }
    public static void add(int a,int b,int c,int d){
        System.out.println("四个int参数的总和: "+ (a+b+c+d));
    }
}

Two, one-dimensional array

1. Array: An array is a collection container that stores data of the same data type.

2. For the statement "int[ ] grade = new int[3]; "

left to right explain
int[ ] grade An array variable of type int is declared, the variable name is grade
int Indicates that the array container can only store data of type int
[ ] This is an array type
grade variable name
= Assignment operator, assigns the memory address of the array object to the grade variable
new int[3] Created an int type array object of length 3
int Indicates that the array object can only store int type data
[ ] This is an array type
3 The array can store up to 3 data, that is, the capacity of the array

3. The benefits of arrays: Assign a number (index value, angle subscript, subscript) to each data allocated to the array object. The range of the index value starts from 0, and the maximum is the array length -1.

class Demo5.5{
    public static void main(String[] args){
        //定义一个数组
        int[] arr = new int[4];
        arr[0] = 10;
        arr[1] = 30;
        arr[2] = 50;
        arr[3] = 90;        
        System.out.println("数组的容量:"+ arr.length);//数组的有一个length的属性,可以查看数组的容量    
        //查看数组中的所有数据
        for(int index = 0 ; index<arr.length ; index++){
            System.out.println(arr[index]);
        }
    }
}

4. Local variables and member variables
◆ Local variables: If a variable is declared inside a method (function), then the variable is a local variable.
◆ Member variables: Member variables are defined outside the method and within the class.
◆ Difference Differences in the location of the
definition :
◇ Member variables are defined outside the method and within the class.
◇ Local variables are defined within the method.
Differences in role:
◇ The role of member variables is to describe the public properties of a class of things.
◇ The role of local variables is to provide a variable for internal use of the method.
Life cycle difference:
◇ exist with the creation of the object, disappear with the disappearance of the object.
◇ A local variable exists when the corresponding method is called and the statement that creates the variable is executed. Once the local variable goes out of its own scope, it immediately disappears from the memory.
The difference between initial values:
◇ member variables have default initial values.
◇ Local variables do not have default initial values ​​and must be initialized before they can be used.

5. The most common problems in arrays
① NullPointerException Null PointerException
Reason : The reference type variable does not point to any object, but the property of the object is accessed or the method of the object is called.
② ArrayIndexOutOfBoundsException The index value is out of bounds
Cause : An index value that does not exist is accessed.

class Demo5.6 {
    public static void main(String[] args){
        /*
        int[] arr = new int[2];
        arr = null;//null让该变量不要引用任何的对象,不要记录任何的内存地址
        arr[1] = 10;
        System.out.println(arr[1]);     
        */
        int[] arr = new int[4];
        arr[0] = 10;
        arr[1] = 30;
        arr[2]  =40;
        arr[3] = 50;
        //System.out.println(arr[4]); //访问索引值为4的内存空间存储的值    
        }
    }
}

6. Array initialization method
① Dynamic initialization: data type [ ] variable name = new data type [length]
② Static initialization: data type [ ] variable name = {element 1, element 2,…..}
Note: if program one You have already determined the data at the beginning, then it is recommended to use static initialization at this time. If the
data is not clear at first, dynamic initialization is recommended at this time.

class Demo5.7 {
    public static void main(String[] args){ 
        //动态初始化
        int[] arr1 = new int[10];   
        //静态初始化
        int[] arr2 = {10,20,30,40,50};

        int[] arr = new int[10];
        Scanner scanner = new Scanner(System.in);
        for(int i  = 0 ; i< arr.length ; i++){
            arr[i] = scanner.nextInt();
        }
        for(int index = 0 ; index<arr.length ; index++){
             System.out.print(arr[index]+",");
        }
    }
}

7. Requirements: Define a function to receive an array object of type int, find the largest element in the array object and return it to the caller.

class Demo5.8 {
    public static void main(String[] args){
        int[] arr = {-12,-14,-5,-26,-4};
        int max = getMax(arr);
        System.out.println("最大值:"+ max); 
    }
    public static int  getMax(int[] arr){
        int max = arr[0]; //用于记录最大值
        for(int i = 1 ; i < arr.length ; i++){
            if(arr[i]>max){ //如果发现有元素比max大,那么max变量就记录该元素
                max = arr[i];
            }
        }
        return max;
    }
}

8. Requirements: Currently there is an array: int[] arr = {0,0,12,1,0,4,6,0}, write a function to receive the array, then clear the 0 of the array, and then return an There is an array of 0 elements.

import java.util.*;
class Demo5.9{
    public static void main(String[] args){
        int[] arr = {0,0,12,1,0,4,6,0};
        arr = clearZero(arr);
        System.out.println("数组的元素:"+Arrays.toString(arr));
    }
    public static  int[] clearZero(int[] arr){
        //统计0的个数
        int count = 0;  //定义一个变量记录0的个数
        for(int i = 0 ; i<arr.length ; i++){
            if(arr[i]==0){
                count++;
            }
        }
        //创建一个新的数组
        int[] newArr = new int[arr.length-count];           
        int index = 0 ; //新数组使用的索引值
        //把非的数据存储到新数组中
        for(int i = 0; i<arr.length ; i++){
            if(arr[i]!=0){
                newArr[index] = arr[i];
                index++;
            }
        }
        return newArr;
    }
}

Three, two-dimensional array

1. Two-dimensional array: A two-dimensional array is an array within an array.

2. Definition format of two-dimensional array
data type [ ][ ] variable name = new data type [length 1][length 2];

3. Two-dimensional array initialization
① Dynamic initialization: data type [ ][ ] variable name = new data type [length 1] [length 2]
② Static initialization: data type [ ][ ] variable name = {{element 1, element2,…},{element1,element2,…},{element1,element2,…} ..}

class Demo5.10{
    public static void main(String[] args){ 
        //定义了一个二维数组
        int[][] arr = new int[3][4];
        arr[1][1] = 100;
        System.out.println("二维数组的长度:"+ arr.length);  //3
        System.out.println("二维数组的长度:"+ arr[1].length); //4
    }
}
class Demo5.11{
    public static void main(String[] args){
        int[][] arr = {{10,11,9},{67,12},{33,35,39,40}};
        //遍历二维数组
        for(int i = 0;  i <arr.length ; i++){
            for(int j = 0 ; j<arr[i].length ; j++){
                System.out.print(arr[i][j]+",");
            }           
            System.out.println();//换行
        }
    }
}

4. Characteristics of
arrays ① The array can only store data of the same data type
② The array assigns an index value to the elements stored in the array, the index value starts from 0, and the maximum index value is length-1
③ Once the array is Initialization, fixed length
④ The memory addresses between elements in the array are consecutive

class Demo5.12{
    public static void main(String[] args){
        int[] arr = new int[3];
        arr = new int[4]; 
        System.out.println(arr.length);//4
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325947019&siteId=291194637