では、プログラミング初心者向けに ユーザーから入力を受け取って配列で処理するミニアプリ を作ってみましょう。
ここでは「5人分のテストの点数を入力して、平均点と最高点を表示する」アプリにします。
サンプルコード:ユーザー入力で配列を処理する
import java.util.Scanner;
public class ScoreApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] scores = new int[5]; // 5人分の点数を入れる配列
// 1. 点数をユーザーから入力
for (int i = 0; i < scores.length; i++) {
System.out.print((i + 1) + "人目の点数を入力してください: ");
scores[i] = sc.nextInt();
}
// 2. 合計点と最高点を計算
int sum = 0;
int max = scores[0]; // 最初の点数を最高点と仮定
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
if (scores[i] > max) {
max = scores[i];
}
}
// 3. 平均点を計算
double average = sum / (double)scores.length;
// 4. 結果を表示
System.out.println("\n--- 結果 ---");
System.out.println("平均点: " + average);
System.out.println("最高点: " + max);
sc.close();
}
}
Java実行例
1人目の点数を入力してください: 80
2人目の点数を入力してください: 90
3人目の点数を入力してください: 75
4人目の点数を入力してください: 60
5人目の点数を入力してください: 85
--- 結果 ---
平均点: 78.0
最高点: 90
解説
Scannerを使ってユーザーから数値を入力int[] scores = new int[5];で5人分の点数を入れる配列を作るforループ で配列に入力値を順番に代入- 合計・最高点の計算
- 合計は
sum += scores[i]; - 最高点は
if (scores[i] > max)で更新
- 合計は
- 平均点は double 型にキャストして計算
- 結果を表示
💡ポイント:
- 配列の要素数が変わる場合は、
scores.lengthを使うと自動的に対応できる - 配列とループを組み合わせると、複数のデータを効率よく扱える
