我需要使用可比较的 interfact 和 compareTo 方法按字母顺序对学生列表进行排序,然后按考试成绩排序。我正在努力让它在我的应用程序中工作。
需要从文本文件中读取名称列表。我不知道我的教授使用的文本文件中有多少个名字,除了它会少于 100 个。我还应该在底部显示平均成绩,并在任何旁边写一条消息低于平均水平 15 分的学生。我还没有真正进入写作信息部分,因为我目前正忙于获取姓名和分数以进行打印和排序。
文本文件应如下所示:
钢铁侠安德里亚 95
穆拉赫乔尔 98
洛道格 82
穆拉赫迈克 93
这就是我到目前为止所拥有的......如果有人能给我一些指导,我将不胜感激。谢谢你。
package chapt11;
import java.io.FileReader;
import java.util.Arrays;
importjava.util.Scanner;
public class CH11AS8App {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
Scanner aScanner = new Scanner(new FileReader(
"src//chapt11//ch11AS8data.txt"));
Student [] studentArray;
String lastName;
String firstName;
int examScore = 0;
double average = 0;
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
while (aScanner.hasNext()) {
lastName = aScanner.next();
firstName = aScanner.next();
examScore = aScanner.nextInt();
System.out.println("Student " + nStudent++ + " " + firstName
+ " " + lastName + " " + +examScore);
studentArray[i] = new Student(lastName, firstName, examScore);
}
double sum = 0.0;
sum += examScore;
average = sum/nStudent;
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (examScore<= (average-10))
{
System.out.println ("Score 10 points under average");
}
System.out.println("Student Average:" +average);
}
}
}
public interface Comparable {
int compareTo(Object o);
}
class Student implements Comparable {
private String firstName;
private String lastName;
private int examScore;
public Student(String firstName, String lastName, int examScore) {
this.firstName = firstName;
this.examScore = examScore;
this.lastName = lastName;
}
// Get & Set Methods
public int getExamScore() {
return examScore;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public int compareTo(Object o) {
Student s = (Student) o;
if (s.lastName.equals(lastName)) {
return firstName.compareToIgnoreCase(s.firstName);
} else {
return lastName.compareToIgnoreCase(s.lastName);
}
}
public String toString() {
return lastName + ", " + firstName + ": " + examScore;
}
}
}