Java测试编程题

开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-5-17

1、假设1701班有40个学生,学号为170101~170140,全部参加语文、数学、英语三门考试,给出所有同学的各科成绩(成绩为整数、随机产生,范围为 [50,100]),并求出每位同学的总成绩。请编写程序将1701班各位同学的总成绩从高到低排序,并使用IO流的知识的把成绩写入到G:\StudentScore.txt文件中。
注:成绩相同时学号较小的先打印;要求:
① 打印的信息包含学号、姓名(姓名统一为“同学 X”[X=01,02,03,…]和学号后两位一致)和成绩,具体格式参考下面截图。
② 遍历数组时使用迭代器
代码如下:
package com.gx.ceshi;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class CeShi {
public static void main(String[] args) throws IOException {
List chengJi = new ArrayList();
//声明变量
int xueHao2=170100,yuWen2,shuXue2,yingYu2,zongFen2;
String xingMing2;
Random random =new Random();//伪随机数类
//生成40条数据
for (int i = 1; i < 41; i++) {
xueHao2++;//学号
xingMing2=String.valueOf(i);//姓名
if(xingMing2.length()<2){
xingMing2=“同学 0”+xingMing2;
}else{
xingMing2=“同学 “+xingMing2;
}
yuWen2=random.nextInt(51)+50;//语文成绩
shuXue2=random.nextInt(51)+50;//数学成绩
yingYu2=random.nextInt(51)+50;//英语成绩
zongFen2 = yuWen2+shuXue2+yingYu2;//总分
chengJi.add(new ChengJi(xueHao2,xingMing2,yuWen2,shuXue2,yingYu2,zongFen2));
}
Collections.sort(chengJi);//排序
//创建文件
File file =new File(“G:\StudentScore.txt”);
if(!file.exists()){
file.createNewFile();
}
//处理流
PrintWriter printWriter = new PrintWriter(file);
//写入文件
Iterator iterator =chengJi.iterator();
while(iterator.hasNext()){
ChengJi chengJi2 = iterator.next();
//println:每输入一次会换行,write:不会换行,直接拼接数据的
printWriter.println(“学号:”+chengJi2.getXueHao()+”,姓名:”+chengJi2.getXingMing()+",语文:"+chengJi2.getYuWen()+
“,数学:”+chengJi2.getShuXue()+",英语:"+chengJi2.getYingYu()+",总分:"+chengJi2.getZongFen());
}
printWriter.close();
System.out.print(“打印完成!”);
}
}
class ChengJi implements Comparable{
private int xueHao, yuWen, shuXue, yingYu, zongFen;
private String xingMing;
public ChengJi(int xueHao, String xingMing, int yuWen, int shuXue,
int yingYu, int zongFen) {
this.xueHao = xueHao;
this.xingMing = xingMing;
this.yuWen = yuWen;
this.shuXue = shuXue;
this.yingYu = yingYu;
this.zongFen = zongFen;
}
public int getXueHao() {
return xueHao;
}
public void setXueHao(int xueHao) {
this.xueHao = xueHao;
}
public String getXingMing() {
return xingMing;
}
public void setXingMing(String xingMing) {
this.xingMing = xingMing;
}
public int getYuWen() {
return yuWen;
}
public void setYuWen(int yuWen) {
this.yuWen = yuWen;
}
public int getShuXue() {
return shuXue;
}
public void setShuXue(int shuXue) {
this.shuXue = shuXue;
}
public int getYingYu() {
return yingYu;
}
public void setYingYu(int yingYu) {
this.yingYu = yingYu;
}
public int getZongFen() {
return zongFen;
}
public void setZongFen(int zongFen) {
this.zongFen = zongFen;
}
//排序方法
@Override
public int compareTo(ChengJi o) {
if(this.zongFen!=o.zongFen){
return o.zongFen-this.zongFen;
}else{
return this.xueHao - o.xueHao;
}
}}

你可能感兴趣的:(Java测试编程题)