Java输入若干个学生成绩

从键盘上输入若干个学生的成绩,统计并输出最高成绩、最低成绩和平均成绩,当输入负数时结束输入。


package com.work;

import java.util.Scanner;

/**
 * @author: By yangbocsu
 * @date: 2021/9/22 
 * @description:
 */
public class sum {
    public static void main(String[] args) {
        float score=0;
        float sum = 0;
        float max = 0;
        float min = 0;
        float average = 0l;
        int cnt = 0;

        Scanner in = new Scanner(System.in);
        while (true)
        {
            score = in.nextInt();
            if (score == -1)
                break;
            sum += score;
            if(score > max)
                max = score;
            else if (score < min)
                min = score;
            cnt++;
        }
        average = sum/cnt;
        System.out.println("最高成绩 = " + max);
        System.out.println("最低成绩 = " + min);
        System.out.println("平均成绩 = " + average);

    }

}

img


//从键盘上输入若干个学生的成绩,统计并输出最高成绩、最低成绩和平均成绩,当输入负数时结束输入。
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Double> list = new ArrayList<>();
        int i = 1;
        while (true){
            System.out.println("请输入第"+ i++ +"个成绩:");
            double  score = sc.nextDouble();
            if (score<0){
                break;
            }else {
                Double it = score;
                list.add(it);
            }
        }
        double max = 0;
        double min = list.get(0);
        double sum = 0.0;
        for (int j = 0; j  < list.size(); j++) {
            sum = sum + list.get(j);
            if (list.get(j)>max){
                max= list.get(j);
            }
            if (list.get(j)<min){
                min = list.get(j);
            }
        }
        System.out.println("最高成绩:"+max+"最低成绩:"+min+"平均成绩:"+(sum/list.size()));
    }