题目要求:编写Student类,包括学生的学号no,姓名name,成绩score三个基本属性,以及一个求所有学生总成绩的静态函数sum。使用构造函数对3个学生的基本信息进行初始化,使用静态方法计算3名学生的平均成绩ave。
Student类中的方法根据需要自行定义。
代码演示:
package student; import java.math.BigDecimal; import java.util.*; class Student { int no; String name; int score; static int sum; /*Student(){ }*/ public Student(int no, String name, int score,int sum){ this.no=no; this.name=name; this.score=score; this.sum+=sum; } /* public int getNo(){ return no; } public void setNo(){ this.no=no; } public String getName(){ return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } */ public static int getSum() { return sum; } public static void setSum(int sum) { Student.sum += sum; } public String showInformation(){ return "学号:"+no+",姓名:"+name+",分数:"+score; } public static double ave(){ double ave =Student.sum/3.0; BigDecimal num = new BigDecimal(ave); ave = num.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return ave; } /*public int showScore(){ return sum; }*/ } public class TestStudent{ public static void main(String args[]){ Scanner scan= new Scanner(System.in); Student stu1= new Student(20191145,"小明",100,100); Student stu2 = new Student(20191150,"小王",90,90); Student stu3 = new Student(20191147,"小孙",100,100); System.out.println(stu1.showInformation()+"\n"+stu2.showInformation()+"\n"+stu3.showInformation()); System.out.println("分数总和为:"+Student.getSum()); System.out.println("三名学生的平均值为:"+Student.ave()); } }
运行截图: