bug记录贴
题目要求如下:
Main类:在main方法中,调用constructStudentList方法构建一个Worker对象链表,调用computeAverageScore方法计算一个班级的平均分并输出到屏幕。 根据要求,编写Student类和StudentList类。
Student类的编程要求如下:
成员变量包括:学生姓名(String name)、班级编码(String classCode)、分数(int score)
根据程序需求编写构造方法。
根据程序需求编写set和get方法。
StudentList类的编程要求如下:
根据程序需求编写构造方法。
constructStudentList方法:调用readInStudent方法读入多个学生信息,将Student对象添加到链表中,构建一个Student对象链表,最后返回链表。
readInStudent方法:使用scanner从键盘读入一个学生的姓名、班级和分数,构建一个Student对象并返回。
computeAverageScore(List list)方法:遍历链表,累加链表中所有学生人数和总分数,计算出某个班级平均分并返回。
接口定义
List<Student> constructStudentList();
Student readInStudent();
double computeAverageScore(List<Student> list);
裁判程序
import java.util.*;
public class Main {
public static void main(String[] args) {
StudentList sl=new StudentList();
List<Student> list=sl.constructStudentList();
System.out.println(sl.computeAverageScore(list));
}
}
/* 请在这里填写答案 */
/*请在这里补充Student类*/
/*请在这里补充StudentList类*/
先贴上正确答案
class Student1{
String name;
String classCode;
int score;
public Student1(){}
public Student1(String name,String classCode,int score){
this.name = name;
this.classCode = classCode;
this.score =score;
}
public String getClassCode(){
return classCode;
}
public int getScore(){
return score;
}
}
class StudentList{
private Scanner sc;//公用输入流
public String NeedClassCode;
List<Student1> constructStudentList(){
sc = new Scanner(System.in);
NeedClassCode = sc.next();//大坑
List<Student1> Stus = new ArrayList<>();
Student1 Stu = readInStudent();
while(Stu != null){
if(Stu.getClassCode().equals(NeedClassCode))
Stus.add(Stu);
Stu = readInStudent();
}
sc.close();
return Stus;
}
Student1 readInStudent(){
//Scanner sc = new Scanner(System.in);//大坑
String name = sc.next();
if(name.equals("#")){
return null;
}
String classCode = sc.next();
int score = sc.nextInt();
return new Student1(name,classCode,score);
}
double computeAverageScore(List<Student1> list){
ListIterator<Student1> i=list.listIterator();
double sum = 0;
while(i.hasNext()){
int x = i.next().getScore();
sum+=x;
}
return sum/list.size();
}
}
最开始的思路是先把所有的数据录入list,在遍历的时候比较classCode再进行平均数的计算,没想到从这开始就有问题了…
因为要比较classCode和计算score就在迭代器中同时用到了 i.next().getClassCode() 和 i.next().getScore().结果测试的时候一直报溢出错误(找不到相应的值),后来查过了才知道 next() 方法每执行一次就会自动换到下一个元素.其实用脑子想想也能知道,这里错了确实是我脑抽了
于是换换思路把classCode的比较放在list读取元素那,只把对应班级的人放进去
这里也是因为看到CSDN一位同学的做法,借鉴了,然后他还特别在Scanner那标注了有坑,我当时看了下只当是close的问题,因为他好像没写close,然后就自己成功的再走了一遍他的坑…
这个问题就是,由于我们的先读取一个classCode作为计算平均分的标志,然后剩下的数据读取是由另外一个函数操作的,所以我在两个函数中都有一个Scanner,在平时测试时这完全没问题吧.因为我们的数据都是一个一个输进去的,但pta不行,pta是想剪贴板一样贴上去的,所以我们的第一个Scanner就会直接把所有流里的数据全读掉了,导致第二个函数里想要读数据只能重新输…
解决方案:
由于输入的数据只能被一个Scanner读取,那我们直接把他做成公用的就好了,两个函数都用这一个Scanner就行…
虽然解决方法很简单,但这错误真的阴间,找了我好久,麻了
本文讲述了在Java中如何修复因多次创建Scanner导致的数据读取问题,通过共享一个Scanner对象来读取学生信息,并计算特定班级的平均分。作者详细描述了问题出现的原因、解决思路和最终的代码实现。

被折叠的 条评论
为什么被折叠?



