LoginSignup
0
0

More than 3 years have passed since last update.

備忘録No.5「HashMapの値にクラスを使って複数持たせる」[Java]

Posted at

やりたい事

1.生徒の数と合格点を入力
2.テストの点数と欠席回数を生徒の数入力し、テストの点数から欠席回数 * 5点を引いたものが合格点を超えている生徒をピックアップして表示

コード

        Scanner sc = new Scanner(System.in);
        int ppl = sc.nextInt(); //生徒の数
        int ps = sc.nextInt(); //合格点


        Map<Integer, Stud> map = new LinkedHashMap<>(); //学籍番号とStudクラスを持たせる
        for(int i = 1; i <= ppl; i++) {
            int a = sc.nextInt(); //テストの点数
            int b = sc.nextInt(); //欠席回数
            Stud s = new Stud(a, b); //インスタンス化
            map.put(i, s); //学籍番号とインスタンスをマップにつめる
        }

        for(int key : map.keySet()) {
            Stud c = map.get(key);
            int d = c.score; //学籍番号ごとの点数
            int e = c.absent; //欠席回数
            int f = d - e * 5; // 最終的な点数を計算
            if(f <= 0) { //計算の結果、点数がマイナスになった場合、0点を下限にする
                f = 0;
            }

            if(f >= ps) {
                System.out.println(key);
            }
        }
    }
}


class Stud { //生徒クラス
        int score; //点数
        int absent; //欠席回数

        public Stud(int score, int absent) {
            this.score = score;
            this.absent = absent;
        }
}

感想

配列を使ったやり方を最初に思いついたが、複雑な形になりそうだったので、Mapを使ってみた。詰めた順に取り出したかったので、LinkedHashMapを使った。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0