要求:显示学生基本信息(学号,姓名,性别,成绩)并按照成绩统计各个级别的人数。
代码如下:
建立Student类定义学生属性。
public class Student {
private String id;
private String sex;
private String name;
private int score;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
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;
}
}
建立BuildStu类,设计创建Student类的数组并附初值的方法。
public class BuildStu {
public Student[] getStu(){
Student[] stu = new Student[5];
//stu0
Student s = new Student();
s.setId("000");
s.setName("张三");
s.setSex("男");
s.setScore(60);
stu[0] = s;
//stu1
Student s1 = new Student();
s1.setId("001");
s1.setName("李四");
s1.setSex("男");
s1.setScore(90);
stu[1] = s1;
//stu2
Student s2 = new Student();
s2.setId("002");
s2.setName("赵五");
s2.setSex("女");
s2.setScore(89);
stu[2] = s2;
//stu3
Student s3 = new Student();
s3.setId("003");
s3.setName("王六");
s3.setSex("女");
s3.setScore(89);
stu[3] = s3;
//stu4
Student s4 = new Student();
s4.setId("004");
s4.setName("孙七");
s4.setSex("女");
s4.setScore(89);
stu[4] = s4;
return stu;
}
}
建立Method类,创建输出成绩并按照成绩划分等级的方法。
public class Method {
public void fun(Student[] stu){
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int E = 0;
for(int i = 0;i<stu.length;i++)
{
if(stu[i]!=null){
System.out.println(stu[i].getName() + "----成绩"+ stu[i].getScore() );
}
}
for(int j=0;j<stu.length;j++)
{
if(stu[j]!=null){
switch(stu[j].getScore()/10){
case 9:{
A++;
System.out.println(stu[j].getName()+"等级为A");
break;
}
case 8:{
B++;
System.out.println(stu[j].getName()+"等级为B");
break;
}
case 7:{
C++;
System.out.println(stu[j].getName()+"等级为C");
break;
}
case 6:{
D++;
System.out.println(stu[j].getName()+"等级为D");
break;
}
default:{
E++;
System.out.println(stu[j].getName()+"等级为E");
break;
}
}
}
}
System.out.println("得A人数为" +A);
System.out.println("得B人数为" +B );
System.out.println("得C人数为" +C );
System.out.println("得D人数为" +D );
System.out.println("得E人数为" +E );
}
}
定义主函数。
public class Main {
public static void main(String [] args){
BuildStu stuarr=new BuildStu();
Student[] stu=new Student[5];
stu=stuarr.getStu();
Method met =new Method();
met.fun(stu);
}
}
运行结果为,如图: