java笔记2-数组操作

目录

遍历数组

数组排序

二维数组

命令行参数


遍历数组

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {
		int[] ns = { 1, 1, 2, 3, 5, 8 };
		System.out.println(ns); // 类似 [I@7852e922
		// 使用for循环可以遍历数组
		for (int i = 0; i < ns.length; i++) {
			int n = ns[i];
			System.out.println(n);
		}
		// for each循环直接遍历数组的元素
		for (int n : ns) {
			System.out.println(n);
		}
		System.out.println(Arrays.toString(ns));
	}

}

数组排序

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {
		/**
		 * 冒泡法
		 */
		int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
		// 排序前:
		System.out.println(Arrays.toString(ns));
		// 排序:
		for (int i = 0; i < ns.length; i++) {
			for (int j = i + 1; j < ns.length; j++) {
				if (ns[i] > ns[j]) {
					// 交换ns[i]和ns[j]:
					int tmp = ns[j];
					ns[j] = ns[i];
					ns[i] = tmp;
				}
			}
		}
		// 排序后:
		System.out.println(Arrays.toString(ns));

		/**
		 * 使用Arrays.sort
		 */
		int[] ns1 = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
		// 排序前:
		System.out.println(Arrays.toString(ns1));
		// 排序
		Arrays.sort(ns1);
		// 排序后:
		System.out.println(Arrays.toString(ns));

	}

}

二维数组

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {
		int[][] stds = {
				// 语文, 数学, 英语, 体育
				{ 68, 79, 95, 81 }, { 91, 89, 53, 72 }, { 77, 90, 87, 83 }, { 92, 98, 89, 85 }, { 94, 75, 73, 80 } };
		System.out.println(stds.length);
		System.out.println(Arrays.toString(stds));
		System.out.println(Arrays.deepToString(stds));
		// TODO: 遍历二维数组,获取每个学生的平均分:
		for (int[] std : stds) {
			int sum = 0;
			for (int s : std) {
				sum = sum + s;
			}
			int avg = sum / std.length;
			System.out.println("Average score: " + avg);
		}
		// TODO: 遍历二维数组,获取语文、数学、英语、体育的平均分:
		int[] sums = { 0, 0, 0, 0 };
		for (int[] std : stds) {
			sums[0] = sums[0] + std[0];
			sums[1] = sums[1] + std[1];
			sums[2] = sums[2] + std[2];
			sums[3] = sums[3] + std[3];

		}
		System.out.println("Average Chinese: " + sums[0] / stds.length);
		System.out.println("Average Math: " + sums[1] / stds.length);
		System.out.println("Average English: " + sums[2] / stds.length);
		System.out.println("Average Physical: " + sums[3] / stds.length);
	}

}

命令行参数

命令行参数是String[]

命令行参数由JVM接收用户输入并传给main方法

如何解析命令行参数由程序自己实现


public class Main {

	public static void main(String[] args) {
		System.out.println("Number of args: " + args.length);
		for (String arg : args) {
			if ("-version".equals(arg))
				System.out.println("version 1.0");
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qwl755/article/details/85000539