(OJ)Java容器-计算平均分

计算平均分

Problem Description

1.实验目的
(1) 掌握容器的创建、使用

2.实验内容
  编写Student类,含分数score属性及相应get、set方法,接着完成类Compute的input方法完成分数输入进Student对象,并存储进容器list,最后完成Compute类的average方法完成容器内的平均分计算。

3.实验要求
  请将下列代码补充完整
  import java.util.*;
  class Compute{
     List<Student> list = new ArrayList<>();
  // 你的代码
  public class Main {
    public static void main(String[] args) {
            Compute comp = new Compute();
            comp.input();
           System.out.println("学生的平均分为:"+ comp.average());
    }
}

Input Description

20,80,52,68,80

Output Description

Student average score: 60

解题代码

// 此题为代码补全题
	// 补全Compute类中的input方法
	public void input(){
    
    
        // 创建Scanner对象
        Scanner in = new Scanner(System.in);
        // 接收控制台输入的一行数据 存储为字符串 输入数据的分隔符为,
        String line = in.nextLine();
        // 切割字符串 获取字符串数组
        String[] scores = line.split(",");
        // 遍历字符串数组 得到每一个分数 字符串
        for (String score: scores){
    
    
            // 将字符串形式的分数转换为int存入List集合
            list.add(new Student(Integer.parseInt(score)));
        }
        // 关闭Scanner对象
        in.close();
    }

	// 计算平均分的方法
    public int average(){
    
    
        // 总分
        int sum = 0;
        // 遍历List集合 累加得到总分
        for (Student s :list){
    
    
            sum += s.getScore();
        }
        // 返回平均分
        return sum/list.size();
    }
}

// Student类
class Student{
    
    
    // 分数属性
    private int score;

    // 带参构造器
    public Student(int score) {
    
    
        this.score = score;
    }

    // 无参构造
    public Student() {
    
    
    }

    // get set
    public int getScore() {
    
    
        return score;
    }

    public void setScore(int score) {
    
    
        this.score = score;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112604146
今日推荐