Arrays tools, two-dimensional array

Arrays tools, two-dimensional array

review

1.Idea的使用


2.数组的声明初始化方式
        声明
        int[] arr; 
        int arr[];//不推荐使用
        初始化
        2.1静态初始化
          arr=new int[]{10,20,30};
          int[] arr2=new int[]{3,4,5};
          //简写 必须一条语句完成
          int[] arr3={1,3,5};
        2.2动态初始化
           int[] arr4=new int[4];//创建数组,长度4,数组元素都是默认值 0
          String[] arr5=new String[5];  //创建数组,长度5,数组元素都是默认值null
          
3.数组的使用(元素访问,元素修改,遍历)
          3.1 访问元素  使用下标 ,下标范围 0 - 长度-1
          3.2 获取长度  arr.length;
          3.3 修改元素  
              arr[0]=10;
              arr[1]=20;
              arr[2]=30;
          3.4 数组遍历
            //for
             for(int i=0;i<arr.length;i++){
                    System.out.println(arr[i]);
             }
             //增强for  ,缺点不能访问下标
             for(int num:arr){
                     System.out.println(num);
             }
             注意:1 数组不要越界   ArrayIndexOutofBoundsException
                  2 数组一定要初始化  NullPointerException
          3.5数组内存空间的分配
            栈:存储基本类型数据和引用类型的地址 ,特点:先进后出  空间比较小,访问速度较快
            堆:存储引用类型的实际数据,特点:空间比较大,访问速度较慢
            
            int[] nums=new int[]{20,30,40};
            
            nums 数组 栈 地址
            {20,30,40}存放在堆中
             
4.数组的应用(排序和查找)
     排序:
        4.1 冒泡排序
            N个数字来排列
            两两比较小靠前
            外层循环n-1
            内层循环n-1-i
            for(int i=0;i<nums.length-1;i++){
                for(int j=0;j<nums.length-1-i;j++){
                    if(nums[j]>nums[j+1]){
                       int temp=nums[j];
                       nums[j]=nums[j+1];
                       nums[j+1]=temp;
                    }
                }
            }
        4.2 选择排序
            N个数字来排列
            选择一个来比较
            外层循环n-1
            内层循环小于n
            
            for(int i=0;i<nums.length-1;i++){
                for(int j=i+1;j<nums.length;j++){
                   if(nums[i]>nums[j]){
                     int temp=nums[i];
                     nums[i]=nums[j];
                     nums[j]=temp;
                   }
                }
            }
            
            优化
            
            for(int i=0;i<nums.length-1;i++){
               int k=i;
                for(int j=i+1;j<nums.length;j++){
                   if(nums[k]>nums[j]){
                      k=j; //最小的数的下标
                   }
                }
                if(k!=i){
                   int temp=nums[k];
                   nums[k]=nums[i];
                   nums[i]=temp;
                }
            }
            
        
     查找:
        4.3 顺序查找
            
        4.4 二分法查找
        
            1 先排序
            2 每次从中间开始,进行比较
            
            int low=0;
            int upper=nums.length-1;
            
            while(low<=upper){
               int middle=(low+upper)>>1;
               if(nums[middle]>key){
                  upper=middle-1;
               }else if(nums[middle]<key){
                  low=middle+1;
               }else{
                  return middle;
               }
            }
            return -1;
            

Today content

1.Arrays工具类
2.方法传参和返回值
3.可变参数
4.二维数组
 1.1 二维数组的概念
 1.2 二维数组的定义
 1.3 数组的初始化
 1.4 二维数组的访问
5.调试和文档注释 

teaching objectives

1.掌握Arrays工具类的使用
2.掌握方法传参和返回值
3.掌握可变参数的使用
4.掌握二维数组的初始化和遍历
5.掌握调试和文档注释

Section Arrays Tools

使用帮助文档:
 1.6
 1.8  

作用:主要用于对数组进行排序,查找,填充,比较等的操作
Arrays工具类存在于java.util包下,所以使用的第一步就是导包:import java.util.Arrays;

注意1:如果在同一个Java文件中同时使用Scanner和Arrays,则可以向如下方式导包:
      import java.util.Scanner;
      import java.util.Arrays;

      或者简写为:* 所有的类
      import java.util.*;

注意2:但凡是工具类,类中的方法全部是静态的,方便调用
      调用语法:类名.方法名(实参列表)

Code:

//演示Arrays工具类的使用
package com.qf.day07;

import java.util.Arrays;

/*
 * Arrays工具类的使用
 * 1 二分查找
 * 2 排序
 * 3 复制
 * 4 填充 
 * 5 把数组转成字符串
 *
 * 
 */

public class Demo1 {
    public static void main(String[] args) {
    //  binarySearch();
        //sort();
        //copy();
        //fill();
        toStr();
    }
    //binarySearch 二分查找
    public static void binarySearch() {
        int[] arr=new int[] {5,8,10,20,65,100}; 
        int result=Arrays.binarySearch(arr,22);
        if(result>=0) {
            System.out.println("找到了");
        }else {
            System.out.println("没找到 ");
        }
    }
    //排序
    public static void sort() {
        int[] arr=new int[] {12,8,100,2,9};
        Arrays.sort(arr);
        System.out.println("排序之后:");
        for(int i=0;i<arr.length;i++) {
            System.out.print(arr[i]+" ");   
        }   
    }
    //复制
    public static void copy() {
        int[] arr=new int[] {12,8,100,2,9};
        int[] arr2=Arrays.copyOf(arr, arr.length);
        for(int i=0;i<arr2.length;i++) {
            System.out.println(arr2[i]);
        }
    }
    //填充
    public static void fill() {
        int[] arr=new int[] {12,8,100,2,9};
        Arrays.fill(arr, 10);
        for(int i=0;i<arr.length;i++) {
            System.out.println(arr[i]);
        }
    }
    //把数组转成字符串
    public static void toStr() {
        int[] arr=new int[] {12,8,100,2,9};
        String s=Arrays.toString(arr);
        System.out.println(s);
    }
    
}

Parameter passing and return values ​​of a second method

The parameters there: Reference Method (1) non-parametric method (2)

There is no return value based on: (1) no return value (2) returns a value

2.1 Basic parameters as type of method

Case 1: swap two numbers

public class Demo2 {
    public static void main(String[] args) {
        int num1=10;
        int num2=20;
        swap(num1, num2);
        System.out.println(num1);
        System.out.println(num2);
    }
    public static void swap(int a,int b) {
        System.out.println("交换之前: a:"+a+" b:"+b);
        int temp=a;
        a=b;
        b=temp;
        System.out.println("交换之后: a:"+a+" b:"+b);
    }
}

2.2 reference parameter type as a method of

Case 2: Implement array sort

import java.util.Arrays;

/*
 * 方法的参数传递和返回值
 * 1 交换两个数字
 * 2 实现数组排序
 * 
 */
public class Demo2 {
    public static void main(String[] args) {
        int[] nums=new int[] {15,8,3,9,20,50};
        sort(nums);
        //遍历nums
        System.out.println("遍历nums");
        for(int i=0;i<nums.length;i++) {
            System.out.print(nums[i]+" ");
        }
    }
    
    //2实现数组排序
    public static void sort(int[] arr) {
        //排序之前
        System.out.println("排序之前");
        System.out.println(Arrays.toString(arr));
        //冒泡
        for(int i=0;i<arr.length-1;i++) {
            for(int j=0;j<arr.length-i-1;j++) {
                if(arr[j]>arr[j+1]) {
                    int temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
        //排序之后
        System.out.println("排序之后");
        System.out.println(Arrays.toString(arr));
        
    }
    
}

Summary: Java parameter passing in method is used in the way of traditional values.

1 basic types of actual data transmission

2 is a reference type of transmission address

No effect on the caller after passing basic types of modifications. After passing reference types modify an effect on the caller. Except String and wrapper classes

2.3 Basic type as the return value of the method

Case 3 Write a method to achieve and 1-100, and returns the result

public class Demo3 {

    public static void main(String[] args) {
        int result=sum();
        System.out.println(result);
    }
    
    public static int sum() {
        //计算1-100的和
        int sum=0;
        for(int i=0;i<=100;i++) {
            sum+=i;
        }
        return sum;
    }
}

2.4 reference type as the return value of the method

Case 4: Write a method that returns an array

package com.qf.day07;

import java.util.Arrays;

/*
 * 方法返回值
 * 1 基本类型作为方法返回值
 * 2 引用类型作为方法返回值
 */
public class Demo3 {

    public static void main(String[] args) {
        int[] nums2=getNums();
        for(int i=0;i<nums2.length;i++) {
            System.out.println(nums2[i]);
        }
    }

    //把数组中的每个数字加5,再返回一个数组
    public static int[] getNums() {
        int[] arr=new int[] {5,10,15};
        for(int i=0;i<arr.length;i++) {
            arr[i]=arr[i]+5;
        }
        return arr;
    }
}

Summary: If the return value of the method is the basic type of the actual data is returned, if the reference type is the address is returned.

Special: String type and packaging methods by value and return value follows the basic type.

The third variable parameters

Variable-length parameters

在调用方法时,方法的形参的个数是不确定的
语法
类型... 变量名称
例如:int... num

好处:不用创建数组,直接写数组元素

Code:

package com.qf.day07;
/*
 * 可变参数
 * int...
 * 好处:不用创建数组,直接写数组元素
 * 注意事项:
 * 1 一个方法只能有一个可变参数
 * 2 可变参数只能方法参数列表最后
 */
public class Demo4 {
    public static void main(String[] args) {
        //调用
        //int[] nums= {10,4,8,20};
        //sort(nums);
        sort(10,4,8,20,1,2); //实际运行是,把这些数据变成数组
        
    }
    public static void sort(int a,int... arr) {
        for(int i=0;i<arr.length-1;i++) {
            for(int j=0;j<arr.length-i-1;j++) {
                if(arr[j]>arr[j+1]) {
                    int temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
    }
}

Note:
. A when performing variable length parameter to be used for processing as array

b. a method of only one variable parameter

c. variable parameter method parameter list only the last

Section IV two-dimensional array

4.1 The concept of a two-dimensional array
本质上还是一个一维数组,只是其数组元素又是一个一维数组
    
    举例说明:变量,一维数组,二维数组之间的关系
    吸烟:
    没钱      1根       一个变量
    稍微有钱  一包       一维数组【20根】    
    有钱      一条      二维数组【10包】
4.2 defined two-dimensional array
    方式一:元素类型[][] 数组名称;

    方式二:元素类型 数组名称[][];
    推荐使用方式一
4.3 array initialization
    静态初始化:

    语法:元素类型[][] 数组名称 = new 元素类型[][]{{一维数组1,一维数组2,一维数组3....};
    简化:元素类型[][] 数组名称 =m{{一维数组1,一维数组2,一维数组3....};

    举例:int[][] arr = new int[][]{{2,3},{5,2,1},{10,45,22,54}};
          int[][] arr = {{2,3},{5,2,1},{10,45,22,54}};

    动态初始化:

    语法:元素类型[][] 数组名称 = new 元素类型[二维数组的长度][一维数组的长度]
    举例:int[][] arr = new int[3][4];
    说明:定义一个数组arr,二维数组中一维数组的个数为3个,每个一维数组中元素的个数为4个
4.4 two-dimensional array of access

By specifying the elements of the two-dimensional indexed access

class TwiceArrayDemo01 
{
    public static void main(String[] args) 
    {
        int[][] arr = new int[3][4];

        System.out.println(arr);//[[I@15db9742
        System.out.println(arr.length);//3
        System.out.println(arr[0]);//[I@6d06d69c
        System.out.println(arr[0].length);//4
        System.out.println(Arrays.toString(arr));//[[I@6d06d69c, [I@7852e922, [I@4e25154f]
        System.out.println(Arrays.toString(arr[0]));//[0, 0, 0, 0]

        /*
        [[I@15db9742
        3
        [I@6d06d69c
        4
        [[I@6d06d69c, [I@7852e922, [I@4e25154f]
        [0, 0, 0, 0]
        */
    }
}

Two-dimensional array traversal

//常见的操作:遍历二维数组
class TwiceArrayDemo02 
{
    public static void main(String[] args) 
    {
        //如果二维数组中一维数组的元素个数不确定
        //int[][] arr = new int[3][];

        int[][] arr = new int[][]{{2,3},{5,2,1},{10,45,22,54}};

        //给arr[0]中的第0个元素修改值
        arr[0][0] = 10;

        //遍历arr[0]
        for(int i = 0;i < arr[0].length;i++) {
            System.out.println(arr[0][i]);
        }

        //二维数组的遍历:嵌套for循环
        //简单for循环
        for(int i = 0;i < arr.length;i++) {
            int[] subArr = arr[i];
            for(int j = 0;j < subArr.length;j++) {
                System.out.println(subArr[j]);
            }
        }

        //增强for循环
        for(int[] subArr1:arr) {
            for(int n:subArr1) {
                System.out.println(n);
            }
        }
    }
}

Machine exercise: a class there are two courses, five students, a two-dimensional array holding the results for each course, and calculate the total score and the average score for each course

public static void main(String[] args) {
        double[][] scores=new double[2][5];
        Scanner input=new Scanner(System.in);
        for(int i=0;i<scores.length;i++) {
            for(int j=0;j<scores[i].length;j++) {
                System.out.println("请输入第"+(i+1)+"门课,第"+(j+1)+"个学生的成绩");
                scores[i][j]=input.nextDouble();
            }
        }
        System.out.println("----------------------------");
        for(int i=0;i<scores.length;i++) {
            double sum=0;
            for(int j=0;j<scores[i].length;j++) {
                sum+=scores[i][j];
            }
            System.out.println("第"+(i+1)+"门课的总分是:"+sum);
            System.out.println("第"+(i+1)+"门课的平均分是:"+(sum/5));
            
        }
    }
4.5 two-dimensional array of memory
public static void main(String[] args) {
        int[][] nums={{10,20,30},{40,50,60}};
        int[][] nums2={{1,2},{3,4},{5,6}};
        int[][] nums3=new int[3][2];
        int[][] nums4=new int[2][];
 }

Draw analysis:

Two-dimensional array of memory

Section V: Troubleshooting Tips

Use debugging techniques to help developers understand the process of program execution, to discover and solve problems.

Use eclipse debugger requires two steps:

  • 1 to add a breakpoint:

  • 2 single-step:

    Shortcuts: F5 Step Into Step Into

    Step Over Step Over F6

    F7 Step Return Step Return

    F8 Continue Resume

    View Variables window, Breakpoints window

Use Idea debugger also requires two steps:

  • 1 to add a breakpoint:

  • 2 single-step:

    * 快捷键
    * F8  step over  单步跳过
    * F7  step into  单步进入
    * Alt+Shift + F7 强制单步进入,进入其他的类库

Section VI: Documentation Comments

java in a comment

  • Single-line comments: // this is a single line comment
  • Multi-line comments: / * This is a multi-line comments,

Can be multi-line ** / *

  • JavaDoc NOTE: used to annotate classes, attributes and methods

    使用语法 /** .....*/
  • JavaDoc commonly used tags

label meaning label meaning
@author Author identifies a class, for example @author wgy @version Version of the specified class
@see Specify links or content of reference @param Description of a method parameter
@since Mark a particular variation, @ since jdk1.2 @return Return Type Description
/**
 * 学校类
 * @author wgy
 * @version 2.0 2018/03/20
 */
public class School {
    /** 
    *学校名称
    */
    String schoolName;
    /**
     * 招生方法
     * @return total
     */
    public void drawStudent() {
        System.out.println(schoolName+"开始招生...");
    }
    //...
}

Documentation Comments effects:

Doc comments can be displayed by 1. When prompted to write code

2.JavaDoc annotation tool can extract classes, attributes, methods, etc. from the source code, to form a supporting API help documentation.

Demo 1: eclipse or idea generation Help documentation. Note that encoding -encoding utf-8 -charset utf-8

​ 演示2:javadoc -d doc -encoding utf-8 -charset utf-8 src\com\qf\day23_3\Person.java

to sum up

Use 1 Arrays utility class

binarySearch () // binary search

sort (); // Sort

copyOf (); // copy the array

​ copyOfRange();

fill (); // filled

toString (); // put into a string array to a form

Parameter passing and return value of the method 2

The method of using a parameter passed by value: transmitting the actual data reference types passed basic types of address

The method returns the value 2, the return data, the data base returns the actual type, reference type return address.

3-D array, is actually made up of one-dimensional array, each element of the array is a one-dimensional array.

Statement 4 two-dimensional array, initialization, access (through index access, traversing)

int[][] arr=new int[][]{{10,20},{30,40}}

5 Troubleshooting Tips

1 to add a breakpoint

2 Single step Step Over F5 F6 Step Into F8 continues ctrl + f12 terminates debugging

6 Documentation Comments

Help developers generate API documentation

Dictation

根据下面要求完成题目:
1.分别使用静态初始化和动态初始化的方式定义一个数组
2.对静态初始化的数组分别使用冒泡和选择进行排序,其中,冒泡实现升序,选择实现降序
3.使用for循环和foreach遍历排好序的数组

operation

1.班上有3个学生,每个学生都参加了三门功课的考试,其中第二个学生是特长生,上级要求给他每门功课都+5.【要求:使用二维数组做,并且分别使用for循环和增强for循环遍历二维数组】
2.求一个3*3矩阵对角线元素之和
10  20  30
8   6   7
20  25  50  
  

Interview questions

1.二维数数组在内存中的存储方式是怎样的?

Guess you like

Origin www.cnblogs.com/Zzzxb/p/11369097.html