數據類型[] 數組名; //或者 數組類型 數組名[];
//格式1--先聲明後建立 數據類型[] 數組名; 數組名 = new 數據類型[數組長度]; //格式2--聲明的同時建立數組 數據類型[] 數組名 = new 數據類型[數組長度];
數組名[下標]; //數組下標從0開始
public class ArrayDemo { public static void main(String[] args) { //聲明一個整型數組 int[] intArray; //聲明一個字符串類型的數組 String strArray[]; //建立數組 intArray = new int[5]; strArray = new String[10]; //聲明數組的同時進行建立 float[] floatArray = new float[4]; //初始化數組 char[] charArray = {'a', 'b', 'c', 'd'}; System.out.println("charArray數組的長度爲:" + charArray.length); System.out.println("intArray數組的第二個元素爲:" + intArray[1]); System.out.println("strArray數組的第五個元素爲:" + strArray[4]); System.out.println("floatArray數組的最後一個元素爲:" + floatArray[floatArray.length - 1]); //循環爲整型數組賦值 for (int i = 0; i < 5; i++) { intArray[i] = (i + 1); } //循環輸出整型數組中的元素 System.out.println("整型數組intArray元素爲:"); for (int i = 0; i < 5; i++) { System.out.print(intArray[i] + " "); } } }
案例一:java
import java.util.Scanner; /** * 使用一維數組求整型數組的累加和 */ public class PlusDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //定義整型數組 int[] a = new int[5]; //從鍵盤接收數據,爲數組元素賦值 for (int i = 0; i < a.length; i++) { System.out.println("請輸入第" + (i + 1) + "個元素"); a[i] = sc.nextInt(); } //求數組元素的累加和 int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } System.out.println("數組元素的累加和爲:" + sum); } }
案例二:算法
/** * 求數組元素的最大值 */ public class MaxDemo { public static void main(String[] args) { int[] a = {34, 23, 78, 56, 31}; int max = a[0]; for (int i = 1; i < a.length; i++) { if (max < a[i]) { max = a[i]; } } System.out.println("數組元素的最大值爲:" + max); } }
int[] intArray = {1, 2, 3, 4, 5}; //使用加強型for循環輸出數組元素 for(int n : intArray){ System.out.println(n+" "); }
int a = 3, b = 5; int temp; temp = a; a = b; b = temp;
/** * 使用冒泡排序將一組整數按照從小到大的順序進行排序 */ public class SortDemo { public static void main(String[] args) { //定義須要排序的整形數組 int[] array = {34, 53, 12, 32, 56, 17}; System.out.println("排序前的數組爲:"); for (int n : array) { System.out.print(n + " "); } System.out.println(); int temp; //外重循環控制循環幾回 for (int i = 0; i < (array.length - 1); i++) { //內重循環控制每次排序 for (int j = 0; j < (array.length - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } System.out.println("排序後的數組爲:"); for (int n : array) { System.out.print(n + " "); } } }
之後會補上一篇《常見排序算法》