我需要用可比interfact和compareTo方法来通过测试成绩按字母顺序排序,然后学生的名单。 我挣扎在得到这个在我的应用工作。
需要从一个文本文件中读取名称的列表。 我不知道有多少名字会在我的教授除了使用文本文件,这将是小于100,我也应该显示在底部的评分的平均值,以及接下来的消息写入任何学生是低于平均水平15点。 我还没有真正得到的消息写一部分,我目前停留在获取名字和分数打印和排序。
该文本文件应该是这个样子:
斯蒂尔曼安德烈95
Murach乔尔·98
洛道格·82
Murach迈克·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;
}
}
}