我有这段代码,我正在尝试从addEntry()方法获取用户输入并编写一个方法将其保存到文件中。
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);
}
这是我创建的下面的方法,但文本文件中没有正确的数据,我想我不知何故需要第一种方法中的变量,如“studentIndex”“entryType”等,你能指出我在正确的方向?
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();
}
}
答案 0 :(得分:0)
覆盖toString
类的Person
应该是正确的方法。