【发布时间】:2018-11-07 12:21:22
【问题描述】:
我有一个包含以下数据(学生证、分数)的文件
L0111,80.5
L0222,70.8
L0333,95.4
L0444,67.9
L0555,56.5
我要完成的是使用 ScoreApp 类中的“readStudentData”方法读取它,但以当前在该方法中打印的方式打印它,但通过 printAll() 方法完成。问题是我无法访问“readStudentData”中的“items”数组。除此之外,我无法通过“getMaxScore”方法获得最高分。
我的代码:
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class question5
{
public static void main(String[] args) throws IOException
{
ScoreApp app = new ScoreApp("C:/Users/USER/workspace/Practical 2/Data/data");
app.printAll();
out.println(String.format("%50s", "").replace(' ', '-'));
out.println("Max score: " + app.getMaxScore());
out.println("Average score: " + app.getAverageScore());
out.println("Number of pass scores: " + app.countPassScore());
out.println("Total score (recursion): " +
recursiveGetTotalScore(app.getStudents()));
}
static double recursiveGetTotalScore(List<Student> list)
{
return 0;
}
}
class ScoreApp
{
public static List<Student> students;
public List<Student> getStudents() //getter method
{
return students;
}
public ScoreApp(String data) throws IOException
{
students = new ArrayList<>();
readStudentData(data);
}
private void readStudentData(String data) throws IOException
{
students = new LinkedList<Student>();
Path path = new File(data).toPath();
List<String> content = Files.readAllLines(path);
for(String line : content){
String[] items = line.split(",");
String id = items[0];
double score = Double.valueOf(items[1]);
Student b = new Student(id, score);
out.println(items[0]+": "+items[1]);
}
}
public void printAll()
{
}
public double getMaxScore()
{
double MaxScore = items[1];
for(int i=1;i < items[1].length; i++)
if(items[i] > MaxScore)
MaxScore = items[i];
out.println("Maximum score: " + MaxScore);
}
public double getAverageScore()
{
return 0;
}
public int countPassScore()
{
return 0;
}
}
class Student
{
private String ID;
private double score;
public Student(String ID, double score)
{
this.ID = ID;
this.score = score;
}
public String getID()
{
return this.ID;
}
public void setID(String ID)
{
this.ID = ID;
}
public double getscore()
{
return this.score;
}
public void setscore(double score)
{
this.score = score;
}
}
【问题讨论】:
-
readStudentDatais void 打印出数据是没有意义的。不要让它打印任何东西,而是让它返回一个学生列表。 -
甚至让它仍然没有返回任何内容,因为它填充了一个成员变量。在
printAll中遍历ScoreApp.students并打印每一个(或者让他们自己打印...for (Student student : students) { student.print() } -
记得在
readStudentData的for循环中将b添加到students -
我刚刚尝试了@Tibrogargan,但是通过执行“out.println(student);”在 printAll() 下,我只剩下打印“Student@4e25154f”等。
-
那就给它一个像样的
toString()方法。
标签: java arrays list file arraylist