当前位置: 首页 > 图灵资讯 > 技术篇> 一维数组

一维数组

来源:图灵教育
时间:2023-10-22 16:55:44

定义一维数组数组

  • length:可查看数组的长度
  • 数组的下标从0开始,例如定义了0、1、2、3、4五个元素
  • 数组下标与length的关系:最大值低于length
  • 数组可以通过下标修改数组元素的值
  • 数组未赋值,默认值为0,int默认值为0
////静态定义资料类型[] 变量名 = new 资料类型[]{1,值2,值3 ...};资料类型[] 变量名 = {值1,值2,值3, ...}int[] ages = {22,23,45,26,17};int[] ages1 = new int[]{14,23,45,25,36};///动态定义数据类型[] 变量名 = new 数据类型[数据量];int[] ages2 = new int[5];ages2[0] = 14;ages2[1] = 15;ages2[2] = 13;ages2[3] = 22;ages2[4] = 25;///数组赋值     ctrl + alt  + V变量名[下标] = 值;    ///获取数组数据类型 新变量名 = 变量名[下标];//在这里演示数组定义public class ArrayDemo {public static void main(String[] args) {    ///静态定义    int[] ages = {22, 23, 45, 26, 17};    int[] ages1 = new int[]{14, 23, 45, 25, 36};    //获取数组长度    System.out.println(ages.length);    ///通过数组下标获得数组值    System.out.println(ages[0]);    ///通过数组下标修改元素值    ages[0] = 15;    System.out.println(ages[0]);    ///动态定义    int[] ages2 = new int[5];    ages2[0] = 14;    ages2[1] = 15;    ages2[2] = 13;    ages2[3] = 22;    System.out.println(ages2[3];    System.out.println(ages2[4];    int i = ages2[3];    System.out.println(i);}}
数组遍历
//for 循环遍历变量名.fori    ///foreach变量名.iter    //需求:统计员工年龄之和,年龄最大值,最小值,public的平均值 class ArreyForDemo {    public static void main(String[] args) {        //年龄        int[] ages = {25, 23, 26, 18, 24};        //年龄和        double sum = 0;        //最大值        int max = 0;        //最小值        int min = 0;        //////////////        for (int age : ages) {//            ////年龄求和/////            sum += age;//            ////最大值////            if (max <= age){//                max = age;//        }//            if (min == 0 ||min >= age){//                min = age;//            }        ///for遍历        for (int i = 0; i < ages.length; i++) {            ///年龄求和            sum += ages[i];            //最大值            if (max <= ages[i]) {                max = ages[i];            }            //最小值            if (min == 0 || min >= ages[i]) {                min = ages[i];            }        }        System.out.println("年龄之和:" + sum);        System.out.println("平均年龄:" + (sum / ages.length));        System.out.println("最大年龄值:" + max);        System.out.println("最小年龄值:" + min);    }}
常见错误
  • 数组越界 java.lang.ArrayIndexOutOfBoundsException

  • 空指针异常 java.lang.NullPointerException