Java数组的用法
数组:由类型相同的若干元素组成,下标从0开始;
数组的使用:1.声明数组 2.分配空间 3.赋值 4.处理数据
声明数组:数组类型[] 数组名; e.g. int[] numbers;(也可写作int numbers[];但不推荐)
分配空间:数组名 = new 数组类型[长度]; e.g. score[]=new double[5];
赋值 :数组类型[] 数组名 = new 数组类型[]{以逗号隔开}; e.g. int[] numbers = new int[]{3,7,8,15};
索引越界:下标超过定义的空间长度(最大索引为数组的(空间长度-1))
e.g. int[] score = new int[2];
score[0]=58; score[1]=63; score[2]=95;
因为空间只分配了2个,出现的score[2]就出错了
数组一般和for循环一起使用
定义一个数组并在里面依次输入8个数 | |
数组的排序:Arrays.sort(数组名); //默认为升序