package com.qinhan.array; public class ArrayDemo01 { //变量的类型 变量的名称 = 变量的值 public static void main(String[] args) { int[] nums ; //声明一个数组 nums = new int[10];// 创建一个数组 //给数组元素中赋值 nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = 5; nums[5] = 6; nums[6] = 7; nums[7] = 8; nums[8] = 9; nums[9] = 10; //计算所有元素的和 int sum = 0; //获取数组长度 arrays.length for (int i = 0; i < nums.length; i++){ sum += nums[i]; } System.out.println("总和为:"+sum); } }
package com.qinhan.array; public class ArrayDemo02 { public static void main(String[] args) { //静态初始化: 创建 + 赋值 int[] a = {1,2,3,4,5,6,7,8,9}; System.out.println(a[5]); //动态初始化 : 包含默认初始化 int[] b = new int[10]; b[0] = 1; System.out.println(b[0]); } }
package com.qinhan.array; public class ArrayDemo03 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5,6}; //打印全部的数组元素 for (int i = 0 ; i < arrays.length; i++){ System.out.println(arrays[i]); } System.out.println("==================="); //计算所有元素的总和 int sum = 0; for (int i = 0; i < arrays.length; i++){ sum += arrays[i]; } System.out.println("总和为:"+sum); System.out.println("==================="); //查找最大元素 int max = arrays[0]; for (int i = 0; i < arrays.length; i++){ if (arrays[i]>max){ max = arrays[i]; } } System.out.println("最大值为:"+max); } }
package com.qinhan.array; public class ArrayDemo04 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5,6,7,8}; //JDK1.5 没有下标 // for (int array : arrays) { // System.out.println(array); // } printArray(arrays); int[] reverse = reverse(arrays); printArray(reverse); } //打印数组元素 public static void printArray(int[] arrays){ for (int i = 0; i < arrays.length; i++){ System.out.print(arrays[i]+" "); } } //反转数组 public static int[] reverse(int[] arrays){ int[] result = new int[arrays.length]; //反转的操作 for (int i = 0, j = result.length-1; i < arrays.length ; i++ , j--){ result[j] = arrays[i]; } return result; } }
package com.qinhan.array; public class ArrayDemo05 { public static void main(String[] args) { //[6][2] /* 1,2 arrays[0] 2,3 arrays[1] 3,4 arrays[2] 4,5 arrays[3] 5,6 arrays[4] 6,7 arrays[5] */ int[][] arrays = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}}; //printArray(arrays[0]); // System.out.println(arrays[0][0]); // System.out.println(arrays[0][1]); // System.out.println(arrays.length); // System.out.println(arrays[0].length); for (int i = 0; i < arrays.length ; i++){ for (int j = 0; j < arrays[i].length ;j++){ System.out.println(arrays[i][j]); } } } public static void printArray(int[] arrays){ for (int i = 0; i < arrays.length; i++){ System.out.print(arrays[i]+" "); } } }