数组使用
-
程序案例:
public class ArrayUse { public static void main(String[] args) { int[] arrayInt = {4, 7, 1, 3, 5, 8, 9, 2, 6}; System.out.println("===========打印数组集合==========="); // 打印数组元素 for (int i = 0; i < arrayInt.length; i++) { System.out.print(arrayInt[i] + "\t"); } System.out.println(); System.out.println("===========求数组元素和==========="); // 求数组元素和 int sum = 0; for (int i = 0; i < arrayInt.length; i++) { sum += arrayInt[i]; } System.out.println("sum = " + sum); System.out.println("===========求数组元素最大==========="); // 求数组元素最大 int max = arrayInt[0]; for (int i = 0; i < arrayInt.length; i++) { if (arrayInt[i] > max) { max = arrayInt[i]; } } System.out.println("max = " + max); System.out.println("=======增强For循环-打印数组元素======="); for (int i : arrayInt) { System.out.print(i + "\t"); } System.out.println(); System.out.println("============数组当做入参============"); printArray(arrayInt); System.out.println("============数组排序后返回数组============"); System.out.println("----降序排序----"); // 降序排序 printArray(exeArrayInt(arrayInt, "DESC")); System.out.println("----升序排序----"); // 升序排序 printArray(exeArrayInt(arrayInt, "ASC")); } public static void printArray(int[] arrayInt) { for (int i : arrayInt) { System.out.print(i + "\t"); } System.out.println(); } public static int[] exeArrayInt(int[] arrayInt, String orderBy) { // 将数组元素进行排序从大到小 // 前后数据比较,n个数据需要比较n - 1次 // 此处需要循环8次,并且每循环一次就需要将已经比较出最大的数据进行排除 for (int i = 0; i < arrayInt.length - 1; i++) { for (int j = 0; j < arrayInt.length - 1 - i; j++) { if ("DESC".equals(orderBy)) { if (arrayInt[j] < arrayInt[j + 1]) { int tempNum = arrayInt[j + 1]; arrayInt[j + 1] = arrayInt[j]; arrayInt[j] = tempNum; } } if ("ASC".equals(orderBy)) { if (arrayInt[j] > arrayInt[j + 1]) { int tempNum = arrayInt[j + 1]; arrayInt[j + 1] = arrayInt[j]; arrayInt[j] = tempNum; } } } } return arrayInt; } } // -------------------------------------- // 控制栏输出打印: /** ===========打印数组集合=========== 4 7 1 3 5 8 9 2 6 ===========求数组元素和=========== sum = 45 ===========求数组元素最大=========== max = 9 =======增强For循环-打印数组元素======= 4 7 1 3 5 8 9 2 6 ============数组当做入参============ 4 7 1 3 5 8 9 2 6 ============数组排序后返回数组============ ----降序排序---- 9 8 7 6 5 4 3 2 1 ----升序排序---- 1 2 3 4 5 6 7 8 9 */