Java中数组的简单使用

来源:互联网 发布:手机剪辑视频软件 编辑:程序博客网 时间:2024/05/20 22:01

数组定义:

  1. 相同数据类型的有序结合
  2. 数组也是对象,数组元素相当于对象的成员变量
  3. 数组长度是确定的,不可变得。如果越界,则报错:ArrayIndexOutofBoundException
package tk.javazhangwei.testArray;/*** * 数组的初始化 * @author zw * */public class test01 {    public static void main(String[] args){        int[] a;        int b[];        //创建数组对象        a = new int[4];        b = new int[5];        //默认初始化:数组元素相当于成员变量        //动态初始话        for(int i=0;i<a.length;i++){            a[i] = i*12;            System.out.println(a[i]);        }        //静态初始化        int[] c ={1,2,5,6};        Cars[] cars ={new Cars("奔驰"),new Cars("奥迪")};        Cars c2= new Cars("奔驰");        System.out.println(c2==cars[0]);//两者是不一样的
package tk.javazhangwei.testArray;/** * 测试数组用法 * @author zw * */public class array {    public static void main(String[] args){    int[] a = new int[3];    a[0] = 5;    a[1] = 6;    a[2] = 7;    Cars[] c = new Cars[3];    c[0] = new Cars("奔驰");    System.out.println(c[0].brand);    for(int i=0;i<a.length;i++){        System.out.println(a[i]);    }}}
package tk.javazhangwei.testArray;public class Cars {    String brand;    public  Cars(String brand){        this.brand = brand;    }}
  • 补充说明:JAVA对二维数组的遍历
package tk.zhangwei.array2;/*** * 循环遍历打二维数组 * @author zw * */public class test01 {    public static void main(String[] args){        int[][] a ={{0,1},{4,5,7,8},{9,4}};        a[2][1] = 4;        System.out.println(a[0].length);        for(int i=0;i<=2;i++){            for(int j=0;j<a[i].length;j++){                System.out.print(a[i][j]+" ");            }            System.out.print("\n");        }}}
  • 矩阵加法运算
package tk.zhangwei.array2;/*** * 矩阵加法运算 * 运用方法 * @author zw * */public class Matrix {    //循环打印方法    public static void print(int[][] c){        for(int i=0;i<c.length;i++){            for(int j=0;j<c.length;j++){                System.out.print(c[i][j]+"\t");            }            System.out.print("\n");    }}    //遍历c    public static int[][] add(int[][] a,int[][] b){        int[][] c = new int[a.length][a.length];        for(int i=0;i<c.length;i++){            for(int j=0;j<c.length;j++){                c[i][j]=a[i][j]+b[i][j];            }        }        return c;    }    public static void main(String[] args){        int[][] a ={                {1,3},                {2,4},        };        int [][] b={                {4,5},                {5,5}        };        //调用方法        int[][] c = add(a,b);        print(c);}}
原创粉丝点击