8.5 数组

为什么需要数组?

为了存储多个数据值

什么是数组?

数组是用来存储同一种数据类型多个元素的容器。数据类型:可以是基本类型,也可以是引用类型容器:比如教室、衣柜、纸箱等,可以存放多个事物。

数组定义:

格式一:
数据类型[] 数组名 = new 数据类型[长度]
二:
数据类型[] 数组名 = new 数据类型[]{值1,值2,值3.。。。。};
三:
数据类型[] 数组名 ={值1,值2,值3...}; // 格式三用的多

 需求:定义一个长度为3的int类型的数组
         */
        //格式一
        int[] arr1 = new int[3];
        //二
        int[] arr2= new int[]{1,2,3,};
        //三
        int[] arr3= {1,2,3 };

数组的访问 :
通过数组的索引访问数组的元素
索引:也叫下标、脚标,是数组元素距离数组起始位置的偏移量
第一个元素的偏移量为0,所以数组的索引从0开始
格式︰数组名[索引引
取值:数组名[索引]
赋值︰数组名[索引]=值;

/*
     需求 : 打印数组中的指定元素。
     操作数组中的元素的格式;
      数组名[索引],索引是从0开始的,往后以此类推

 */

public class ArryDemo2 {
    public static void main(String[] args) {
        //1.定义一个数组
        int[] arr={11,22,33};
        System.out.println(arr[2]);

    }
}

结果: 33

数组的遍历:

public class ArrayDemo3 {
    public static void main(String[] args) {
        int []arr={11,22,33,44};
        for (int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }

//  正向遍历
    }
}
public class test1 {
    public static void main(String[] args) {
        int[] ns = {1, 4, 9, 16, 25};
        //倒序打印数组元素
//        for (int i = ns.length - 1; i >= 0; i--) {
//            System.out.println(ns[i] );

        // 倒序打印数组元素:
        for (int i = 0; i < ns.length; i++) {
            System.out.println(ns[ns.length-1-i]);
        }
        }
    }

猜你喜欢

转载自blog.51cto.com/15138685/2666325
8.5
今日推荐