Попытка получить максимальное значение из массива в другом методе при чтении из файла - PullRequest
0 голосов
/ 29 мая 2018

У меня есть файл со следующими данными (идентификатор студента, оценка)

L0111,80.5
L0222,70.8
L0333,95.4
L0444,67.9
L0555,56.5

Я пытаюсь сделать так, чтобы его читали с помощью метода readStudentData в классе ScoreApp,но быть напечатанным так, как он печатается в этом методе в настоящее время, но выполняется методом printAll ().Проблема в том, что я не могу получить доступ к массиву items в readStudentData.Наряду с этим я не могу получить максимальный балл по методу 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;
}
}

1 Ответ

0 голосов
/ 29 мая 2018

У вас уже есть List<Student> students в вашем классе ScoreApp.В вашем методе «readStudentData» вы должны заполнять / вставлять данные в этот список, а в методе «getMaxScore()» вы должны использовать этот список.

public double getMaxScore() {
    double maxScore = 0;
    //"students" is the class variable / list you have in your ScoreApp class
    for(Student current: students) {
        double currentScore = current.getScore();
        if(currentScore > maxScore)
            maxScore = currentScore;
    }
    return maxScore;
}

Обновление: для средней оценки.

public double getAverageScore() {
    double averageScore = 0;
    int noOfStudents = 0;
    int sumOfScores = 0;

    for(Student current: students) {
        double currentScore = current.getScore();
        sumOfScores += currentScore;
        noOfStudents++;
        averageScore = sumOfScores / noOfStudents;
    }
    return averageScore;
}
...