zoukankan      html  css  js  c++  java
  • Java学习笔记3(数组)

    1.数组的定义:

    第一种:

    public class ArrayDemo{
      public static void main(String[] args){
      //定义数组
      int [] arr = new int[3];
      //数组中的元素默认值为0
      System.out.println(arr[0]);
      System.out.println(arr.length);
      }
    }

    这里的length是数组的长度

    第二种定义方法:

    public class ArrayDemo{
      public static void main(String[ ] args){
      //定义数组,注意new后边的中括号不能写数字
      int [ ] arr = new int[ ]{1,2,4,3,6,5};
      System.out.println(arr[4]);
      System.out.println(arr.length);
      }
    }

    第三种(最常用的):

    public class ArrayDemo{
      public static void main(String[ ] args){
      int [ ] arr = {1,2,4,3,6,5};
      System.out.println(arr[4]);
      System.out.println(arr.length);
      }
    }

    两种的结果相同,如下:

    2.数组的赋值:

    arr[1] = 3

    3.遍历

    public class ArrayDemo{
      public static void main(String[] args){
        int [] arr = {2,1,3,5,7,0,4};
        for(int i = 0 ; i < arr.length; i++){
        System.out.println(arr[i]);
        }
      }
    }

    结果:

    4.获取最大值(最小值原理相同):

    public class ArrayDemo{
      public static void main(String[] args){
        int [] arr = {5,-1,2,-4,6,0,8,3};
        int max = arr[0];
        for(int i = 1 ; i < arr.length; i++){
          if( max < arr[i]){
            max = arr[i];
          }
        }
        System.out.println(max);
      }
    }

    5.二维数组:

    定义:

    int  [][] arr = new int [3][4];

    int [][] arr = {{1,2},{3,4,5},{6,7,8,9}};

    内存方法:在堆中存三个一维数组,每个一维数组有四个位置,三个一维数组的首地址存入一个新的数组,这个新数组也有首地址,栈中的arr指向这个地址

    二维数组访问和一维数组类似

    遍历:

    public class ArrayDemo{
      public static void main(String[] args){
        int [][] arr = {{1,2,3},{4,5},{6,7,8,9},{0}};
        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();
        }
      }
    }

  • 相关阅读:
    MATLAB批量打印输出600PPI的图像且图像不留空白
    IC设计基础
    深度学习及图像处理学习路线(一)
    IC设计学习路线
    图像处理算法的仿真平台之VGA时序
    数字IC笔试题芯源
    C++图像处理算法入门前言
    爱因斯坦我的信仰
    linux 设置定时任务执行清理日志脚本
    SpringMVC的工作原理(执行流程)
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8206273.html
Copyright © 2011-2022 走看看