首页 > 解决方案 > 为什么我输入的平均分数没有显示?

问题描述

我是 Java 的新手,不知何故我的代码没有给我平均水平,但它不会给我带来错误,所以我不知道哪里错了。

 System.out.println("Please enter the amount of students: ");
    Scanner sc = new Scanner(System.in);

    int len = sc.nextInt();
    int students[] = new int[len];

    for (int i = 0; i < students.length; i++) {
        System.out.println("Enter the scores from the first examen of the student " + (i + 1) + " ");
        students[i] = sc.nextInt();
    }

    System.out.println("The scores of the students are:" + Arrays.toString(students));
        float scores[] = new float[len];
        int sumScores = 0;
        int count = 0;

        for (int i = 0; i < scores.length; i++) {
            scores[i] = sc.nextInt();
            sumScores += scores[count];
            int average = sumScores / len;
            System.out.println("The average of all the scores are: " + average);

标签: java

解决方案


如果数组和循环让您感到困惑,您也可以尝试函数式编程。

        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter the amount of students: ");
        int len = sc.nextInt();

        double average = IntStream.generate(() -> {
            System.out.println("Enter the scores from the first examen of the student");
            return sc.nextInt();
        }).limit(len).average().orElse(0.0);

        System.out.println("The average of all the scores are: " + average);

推荐阅读