ミニアプリ:ユーザー入力で表(2 次元配列)を作り、合計と平均を計算する
ここでは 「ユーザー入力で行数 × 列数の表を作り、値を入力して集計するミニアプリ」 を、初心者でも動かせるように フルソース+丁寧な説明+動作例 でまとめます。
アプリの仕様(初心者向け)
- 行数(rows)と列数(cols)をユーザーに入力させる
- そのサイズの 2 次元配列 int[][] を作る
- 各セルに入れる値をユーザーに入力させる
- 最後に
- 表の表示
- 行ごとの合計&平均
- 列ごとの合計&平均
を出力する
フルコード(すぐ動く・コメントつき)
import java.util.Scanner;
public class TableApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// --- 1. 行数と列数を入力 ---
System.out.print("行数を入力してください: ");
int rows = sc.nextInt();
System.out.print("列数を入力してください: ");
int cols = sc.nextInt();
// --- 2. 配列の作成 ---
int[][] table = new int[rows][cols];
// --- 3. データ入力 ---
System.out.println("\n値を入力してください(" + rows + "行 × " + cols + "列):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("[" + i + "][" + j + "] = ");
table[i][j] = sc.nextInt();
}
}
// --- 4. 入力された表を表示 ---
System.out.println("\n--- 入力された表 ---");
for (int[] row : table) {
for (int v : row) {
System.out.print(v + "\t");
}
System.out.println();
}
// --- 5. 行ごとの合計と平均 ---
System.out.println("\n--- 行ごとの合計と平均 ---");
for (int i = 0; i < rows; i++) {
int sum = 0;
for (int v : table[i]) {
sum += v;
}
double avg = sum / (double) cols;
System.out.printf("行 %d → 合計=%d, 平均=%.2f%n", i, sum, avg);
}
// --- 6. 列ごとの合計と平均 ---
System.out.println("\n--- 列ごとの合計と平均 ---");
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int i = 0; i < rows; i++) {
sum += table[i][j];
}
double avg = sum / (double) rows;
System.out.printf("列 %d → 合計=%d, 平均=%.2f%n", j, sum, avg);
}
sc.close();
}
}
Java実行例(入力と出力)
ユーザー入力:
行数を入力してください: 2
列数を入力してください: 3
値を入力してください(2行 × 3列):
[0][0] = 10
[0][1] = 20
[0][2] = 30
[1][0] = 40
[1][1] = 50
[1][2] = 60
出力:
--- 入力された表 ---
10 20 30
40 50 60
--- 行ごとの合計と平均 ---
行 0 → 合計=60, 平均=20.00
行 1 → 合計=150, 平均=50.00
--- 列ごとの合計と平均 ---
列 0 → 合計=50, 平均=25.00
列 1 → 合計=70, 平均=35.00
列 2 → 合計=90, 平均=45.00
わかりやすいポイント解説
✔ table = new int[rows][cols]
→ ユーザーが指定したサイズの表が作れる。
✔ table[i][j] = sc.nextInt()
→ 入力した値を表に入れる「代入」。
✔ 行の集計
for (int v : table[i]) sum += v;
✔ 列の集計
行を回す必要があるのでこうなる:
for (int i = 0; i < rows; i++) sum += table[i][j];
