整理Java基礎知識--數組1
阿新 • • 發佈:2018-01-13
sys 4.4 tar 數組 size 大小 sta 理解 ref Java 數組
數組是用來存儲固定大小的同類型的元素
聲明
數組必須先聲明 才能使用
datatype[] arrayRefVar;//首選 []放在最後是為了C/C++的快速理解Java
char[] ch ;或者 char ch[];
char ch = new char[arraySize];
1.創建一個char數組 含有 arraySize元素
2.把新建 char數組的引用 賦值給變量ch
數組的使用
數組是用來存儲固定大小的同類型的元素
聲明
數組必須先聲明 才能使用
datatype[] arrayRefVar;//首選 []放在最後是為了C/C++的快速理解Java
char[] ch ;或者 char ch[];
char ch = new char[arraySize];
1.創建一個char數組 含有 arraySize元素
2.把新建 char數組的引用 賦值給變量ch
數組的使用
public class TestArr{ public static void main(String[] args){ double[] arr = {1.1,2.2,4.4,3.3}; for(double x:arr){ System.out.println(x); }//打印所有數組元素 double total = 0; for(int i = 0;i < arr.length;++i){ total = total + arr[i]; } System.out.println("Total = " + total); //計算並打印所有元素的和 double max = arr[0]; for(int i = 1;i < arr.length;++i ){ if (arr[i] > max) max = arr[i]; } System.out.println("Max = " + max); } //查找並打印最大元素值 } 輸出結果: 1.1 2.2 4.4 3.3 Total = 11.0 Max = 4.4
數組作為函數的參數:
class A{ static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } } public class TestA{ public static void main(String args[]){ int[] arr = {1, 2, 3, 4, 5, 6}; A.printArray(arr); } } 輸出結果: 1 2 3 4 5 6
整理Java基礎知識--數組1