我从硬盘驱动器上的两个文件中获取输入:
studentNames.txt 和 studentScores.txt - 名称包含学生 ID 和姓名,而分数包含学生 ID 和分数。我已将数据放入两个 ArrayLists 中,并希望对数据进行排序,以便成绩转到匹配的 ID。
例如:
+------+--------------+---------+
| ID | Name | Grade |
+------+--------------+---------+
| 3305 | Smith Henry | 92.0 |
| 5555 | Eddy Olivia | 95.5 |
| 8915 | Johnson Luke | 98.5 |
+------+--------------+---------+
并且数据继续仅填充 ID / Grade - 我知道我需要使用 if 语句,但我将如何去做呢?
这是我的代码:
import java.util.*;
import java.io.*;
public class P_Supplemental_9 {
public static void main(String[] args) throws FileNotFoundException {
File file1 = new File("c:/temp/studentNames.txt");
File file2 = new File("c:/temp/studentScores.txt");
if(file1.exists()) {
Scanner input = new Scanner(file1);
ArrayList<Student> students = new ArrayList();
while(input.hasNext()) {
students.add(new Student(input.nextInt(),input.nextLine()));
}
input.close();
for(int o = 0;o < students.size();o++) {
System.out.printf("%10d %20s avg\n", students.get(o).getStuId(), students.get(o).getStuName());
} // end for
}
if(file2.exists()) {
Scanner input = new Scanner(file2);
ArrayList<Student> grades = new ArrayList();
while(input.hasNext()) {
grades.add(new Student(input.nextInt(), input.nextLine()));
} /// end while
input.close();
for(int o = 0;o < grades.size();o++) {
System.out.printf("%10d %20s avg\n", grades.get(o).getStuId(), grades.get(o).getStuName());
} // end for
} // end if(file2.exists)
} // end main method
} // end P_Supplemental_9
class Student {
private int stuId;
private String stuName;
private ArrayList <Double> grades;
Student(int idIn, String nameIn) {
this.stuId = idIn;
this.stuName = nameIn;
} // end student class
Student(int idIn, ArrayList gradesIn) {
this.stuId = idIn;
this.grades = gradesIn;
}
public int getStuId() {
return stuId;
}
/**
* @param stuId the stuId to set
*/
public void setStuId(int stuId) {
this.stuId = stuId;
}
/**
* @return the stuName
*/
public String getStuName() {
return stuName;
}
/**
* @param stuName the stuName to set
*/
public void setStuName(String stuName) {
this.stuName = stuName;
}
/**
* @return the grades
*/
public ArrayList getGrades() {
return grades;
}
/**
* @param grades the grades to set
*/
public void setGrades(ArrayList grades) {
this.grades = grades;
}
} // end student class
这是来自 Studentnames.txt 的数据
3305 Smith Henry
5555 Eddy Olivia
8915 Johnson Luke
这是来自 Studentscores.txt 的数据
3305 92.0
5555 95.5
8915 98.5
3305 89.0
5555 90.5
8915 95.5
3305 78.5
5555 85.0
8915 82.0