Java中数组的简单使用

数组定义:

  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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值