一维数组的使用

1.什么是数组?
        数组是一种特殊的类型,数组的"地址"是首地址,他的值也是首地址。虽然值相同但是类型是不同的。
1.1如何定义一个数组
/**
 * 
 * @author sadfoo @date 2018年8月31日
 * @tips:数组申明、遍历
 */
public class TestArray {

    public static void main(String[] args) {
        // 数组申明或者定义有2种方式:

        // 数组申明
        String[] names;
        // 第一种:静态初始化,初始化数组与给元素赋值同时进行
        names = new String[] { "数组001", "数组002", "数组003" };

        // 数组申明
        int score[];
        // 第二种:动态初始化,初始化数组与给元素赋值分开进行
        score = new int[4];
        // 通过数组元素下角标调用,数组从0开始,n-1结束(n表示数组的长度)
        score[0] = 87;
        score[1] = 88;
        score[3] = 99;

        // 数组的长度,通过数组的length属性来调用
        System.out.println("names的分配空间长度为:" + names.length);
        System.out.println("score的分配空间长度为:" + score.length);
        // 如何遍历数组元素
        // NO1:直接打印脚标遍历(累赘)
        System.out.println("我是names第一种数组遍历方式 :");
        System.out.println(names[0]);
        System.out.println(names[1]);
        System.out.println(names[2]);
        System.out.println("我是score第一种数组遍历方式 :");
        System.out.println(score[0]);
        System.out.println(score[1]);
        System.out.println(score[3]);
        // NO2:循环方法遍历(优选)
        System.out.println("我是names第二种数组遍历方式 :");
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
        System.out.println("我是score第二种数组遍历方式 :");
        for (int i = 0; i < score.length; i++) {
            System.out.println(score[i]);
        }
    }

}

遇到问题:数组下标越界异常

 1.2默认初始化值

// 对于基本数据类型:byte、short、int、long而言,初始默认值为:0
        byte[] bt = new byte[6];
        // 假设赋一个值
        bt[0] = 90;
        bt[5] = 99;
        for (int i = 0; i < bt.length; i++) {
            System.out.println("byte默认值为:" + bt[i]);
        }
        // 对于基本数据类型:float、double而言,初始默认值为:0.0
        float[] ft = new float[7];
        // 假设赋二个值
        ft[1] = 12f;
        ft[3] = 12f;
        for (int i = 0; i < ft.length; i++) {
            System.out.println("float默认值为:" + ft[i]);
        }
        // 对于基本数据类型:char而言,初始默认值为:空格
        char[] cr = new char[8];
        for (int i = 0; i < cr.length; i++) {
            System.out.println("char默认值为:" + cr[i]);
        }
        // 对于基本数据类型:boolean而言,初始默认值为:false
        boolean[] bl = new boolean[9];
        for (int i = 0; i < bl.length; i++) {
            System.out.println("boolean默认值为:" + bl[i]);
        }
        // 对于引用类型的变量构成的数据而言,初始默认值为:null
        // 数组申明
        String[] sr = new String[10];

        sr[0] = "AA";
        sr[1] = "BB";
        sr[3] = "DD";
        for (int i = 0; i < sr.length; i++) {
            System.out.println("引用类型默认值为:" + sr[i]);
        }

1.3数组练习题

猜你喜欢

转载自www.cnblogs.com/sadfoo/p/9563536.html