题解 | 最厉害的学生

最厉害的学生

https://www.nowcoder.com/practice/b6e7a9ca04d8418b805b3b4b7d25b4d4

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        Score[] scores = new Score[N];
        for (int i = 0; i < N; i++) {
            String name = sc.next();
            int c1 = sc.nextInt();
            int c2 = sc.nextInt();
            int c3 = sc.nextInt();
            scores[i] = new Score(name, c1, c2, c3);
        }

        int maxSum = 0; // 最高分
        Score topStudent = null; // 最高分学生的姓名
        for (Score s : scores) {
            // 只有严格大于时才更新(默认是第一个学生)
            if (s.getSum() > maxSum) {
                maxSum = s.getSum();
                topStudent = s;
            }
        }
        System.out.println(topStudent);
    }

    static class Score {
        private String name;
        private int c1;
        private int c2;
        private int c3;

        public Score(String name, int c1, int c2, int c3) {
            this.name = name;
            this.c1 = c1;
            this.c2 = c2;
            this.c3 = c3;
        }

        public int getSum() {
            return c1 + c2 + c3;
        }

        // 重写toString方法(按照输入要求)
        @Override
        public String toString() {
            return name + " " + c1 + " " + c2 + " " + c3;
        }
    }
}

尝试使用hashMap存储姓名和总分,太复杂了搞不定。。。

全部评论

相关推荐

评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务