Java数组
Java中,数组是用来存储固定大小的同类型元素。
声明数组变量
声明语法:
dataType[] arrayRefVar; //首选方法 dataType arrayRefVar[]; //效果相同,但不是首选
例:
double[] myList; double myList[];
创建数组
语法:
arrayRefVar = new dataType[arraySize];
数组的元素是可以通过索引访问的,数组索引从0开始,数组的索引值从0到arrayRefVar.length-1.
实例:
1 public class TestArray { 2 public static void main(String[] args){ 3 //数组大小 4 int size = 10; 5 //创建数组 6 double[] myList = new double[size]; 7 myList[0] = 1.3; 8 myList[1] = 1.31; 9 myList[2] = 33; 10 myList[3] = 5.3; 11 myList[4] = 6.3; 12 double total = 0; 13 //for循环计算数组和 14 for (int i = 0; i <size; i++){ 15 total += myList[i]; 16 } 17 System.out.println("total is " + total); 18 } 19 }
处理数组
数组处理,我们通常使用for-each循环处理;
实例:
1 public class TestArray1 { 2 public static void main(String[] args){ 3 double[] myList = {1.5, 2.4, 1.9, 22, 4.5, 12}; 4 //打印所有元素 5 for (int i = 0; i < myList.length; i++){ 6 System.out.println(myList[i]+" "); 7 } 8 //计算数组总和 9 double total = 0; 10 for (int i = 0; i < myList.length; i++){ 11 total += myList[i]; 12 } 13 System.out.println("total is "+ total); 14 //查找最大元素 15 double max = 0; 16 for (int i = 0; i < myList.length; i++){ 17 if (myList[i] > max){ 18 max = myList[i]; 19 } 20 } 21 System.out.println("max is " + max); 22 23 } 24 }
for-each循环
public class TestArray2 { public static void main(String[] args){ double[] myList = {1.8, 23, 2.0, 4, 44}; //打印所有数组元素 for (double element : myList){ System.out.println(element); } } }
标签:myList,int,double,数组,Java,total,public From: https://www.cnblogs.com/wenzm/p/17383230.html