0

I have this code, that I'm trying to take the user input from the addEntry() method and write a method to save that to file.

public class GradeBook {

private String course;
private ArrayList<Person> students = new ArrayList<Person>();
private ArrayList<GradeBookEntry> entries = new ArrayList<GradeBookEntry>();

public GradeBook(String course){
    this.course = course;
}

public String getCourse() {
    return course;
}

public void setCourse(String course) {
    this.course = course;
}

public void addStudent( Person student ){
    students.add(student);
}

public void addEntry(){
    System.out.println("Grade which student: ");
    for (int i = 0; i < students.size(); i++) {
        System.out.println(i + " " + students.get(i).getName());
    }
    Scanner reader = new Scanner(System.in);
    int studentIndex = reader.nextInt();
    reader.nextLine();

    System.out.println("Enter the assessment name: ");
    String assessmentName = reader.nextLine();

    System.out.println("Homework (1) or exam (2): ");
    int entryType = reader.nextInt();
    reader.nextLine();

    GradeBookEntry newEntry;
    // TODO: create either a Homework or Exam entry
    if( entryType == 1 ){
        newEntry = new HomeworkEntry(assessmentName);
    }
    else {
        newEntry = new ExamEntry(assessmentName);
    }

    // TODO: add getData method to the Homework and Exam
    newEntry.getData();
    newEntry.setStudent(students.get(studentIndex));

    entries.add(newEntry);
}

This is the method below that I created but the text file doesnt have the correct data in it, I guess I somehow need the variables from the first method like "studentIndex" "entryType" etc., can you point me in the right direction?

public void writeFile(String fileName){
    try {
        FileWriter writer = new FileWriter(fileName);
        for (int i=0; i<entries.size(); i++){
            writer.write(students.get(i).toString());
        }
                    writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Fireguyy
  • 1
  • 1
  • These were my instructions: Add a method to the GradeBook that saves its entries. ◦Put each entry on its own line, with a separator between values. I'm interpreting that as saving the user input asked from addEntry() but I don't know how to get those variables so that I can save them. – Fireguyy Mar 12 '15 at 02:54

1 Answers1

0

Overriding toString of Person class should be the correct way to go about this.

Ajay George
  • 11,759
  • 1
  • 40
  • 48
  • I'm not quite sure how I would do that? would it just be a method public String toString() { return studentIndex} – Fireguyy Mar 12 '15 at 02:44
  • [This](http://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java) could be a start. – Ajay George Mar 12 '15 at 02:44