Javaで配列の操作

概要

配列に保存された数値にいろいろ処理をする。

public class IntegerArrayTest {
	public static void main(String[] args) {
		int[] array;
		array = new int[] { 100, 90, 10, 80, 20, 70, 30, 60, 40, 50, 0 };
		int length, Total = 0, i = 0, j = 0, maxValue = 0, minValue = 0, tmp;
		double Average;
		length = array.length;

		System.out.println("***配列操作プログラム***");
		System.out.println("配列の要素数:     " + length);
		System.out.println("***配列の内容表示(初期状態)***");

		maxValue = minValue = array[i];

		for (i = 0; i < length; i++) {
			if (array[i] > maxValue) {
				maxValue = array[i];
			} else if (array[i] < minValue) {
				minValue = array[i];
			}
			System.out.print("   [" + i + "]  " + array[i]);
			Total += array[i];
			if ((i + 1) % 3 == 0) {
				System.out.println("");
			}
		}
		System.out.println();
		Average = Total / i;
		for (i = 0; i < length - 1; i++) {
			for (j = i + 1; j < length; j++) {
				if (array[i] > array[j]) {
					tmp = array[i];
					array[i] = array[j];
					array[j] = tmp;
				}
			}
		}
		System.out.println("***配列の内容表示(昇順)***");
		for (i = 0; i < length; i++) {
			System.out.print("   [" + i + "]   " + array[i]);
			Total += array[i];
			if ((i + 1) % 3 == 0) {
				System.out.println("");
			}
		}
		System.out.println("");
		for (i = 0; i < length - 1; i++) {
			for (j = i + 1; j < length; j++) {
				if (array[i] < array[j]) {
					tmp = array[i];
					array[i] = array[j];
					array[j] = tmp;
				}
			}
		}
		System.out.println("***配列の内容表示(降順)***");
		for (i = 0; i < length; i++) {
			System.out.print("   [" + i + "]   " + array[i]);
			Total += array[i];
			if ((i + 1) % 3 == 0) {
				System.out.println("");
			}
		}
		System.out.println("");
		System.out.println("***配列の統計情報***");
		System.out.print("最小値=" + minValue + "  ");
		System.out.print("最大値=" + maxValue + "  ");
		System.out.println("平均値=" + Average);
		System.out.println("***プログラム終了***");
	}
}

実行結果

配列操作プログラム***

配列の要素数: 11

配列の内容表示(初期状態)***

[0] 100 [1] 90 [2] 10
[3] 80 [4] 20 [5] 70
[6] 30 [7] 60 [8] 40
[9] 50 [10] 0

配列の内容表示(昇順)***

[0] 0 [1] 10 [2] 20
[3] 30 [4] 40 [5] 50
[6] 60 [7] 70 [8] 80
[9] 90 [10] 100

配列の内容表示(降順)***

[0] 100 [1] 90 [2] 80
[3] 70 [4] 60 [5] 50
[6] 40 [7] 30 [8] 20
[9] 10 [10] 0

配列の統計情報***

最小値=0 最大値=100 平均値=50.0

プログラム終了***