java 使用数组按姓名和分数对学生进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13337667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting students by name and score using an array
提问by newB
I posted a question about this last night but am still struggling. I need to sort a list of students from a text file first by name (in this format last name, first name), and then by test scores. I won't know how many students will be in the text file, other than that there is less than 100. I have to use the compareTo method (which I think I did correctly) and an array (I don't think I'm using this correctly). I have been messing around with this for literally hours on end and I just don't seem to get it. The text book really doesn't seem to be helping me any. How can I get my app class to print sorted student names/grades?
我昨晚发布了一个关于这个的问题,但仍在挣扎。我需要首先按姓名(采用这种格式姓,名),然后按考试成绩对文本文件中的学生列表进行排序。我不知道文本文件中有多少学生,除了少于 100 个。我必须使用 compareTo 方法(我认为我做对了)和一个数组(我不认为我我正确使用它)。我已经连续几个小时搞乱了这个问题,但我似乎不明白。教科书似乎真的没有帮助我。如何让我的应用程序类打印排序的学生姓名/成绩?
Other spefications are to get the average of the scores and make a comment next to any score below average. Those, however, I can work on after I can get the sorting straightened out.
其他规范是获取分数的平均值并在任何低于平均值的分数旁边发表评论。然而,在我整理好分类之后,我可以继续工作。
Here is my code...
这是我的代码...
package CH11AS8App;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class kjkkkkkkkkkkk {
public static void main( String[] args ) throws Exception {
// TODO Auto-generated method stub
Scanner aScanner = new Scanner(
new FileReader("src//chapt11//ch11AS8data.txt"));
int numOfStudents = 100;
Student[] studentArray = new Student[numOfStudents];
Scanner sc = null;
int counter = 0;
while (aScanner.hasNext()) {
sc = new Scanner(aScanner.nextLine());
String lastName = sc.next();
String firstName = sc.next();
int score = sc.nextInt();
studentArray[counter++] = new Student(lastName, firstName, score);
studentArray[counter] = new Student(lastName, firstName, score);
int average= 0;
int sum = 0;
sum += score;
if (counter < numOfStudents);
average = sum / counter;
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
System.out.println("Student Average:" + average);
}
sc.close();
// Display Welcome Message
System.out.println("Welcome to the Student Scores Application.\n");
//Sort Names
Arrays.sort(studentArray,0,counter, new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2) {
return s1.getLastName().compareTo(s2.getLastName());
}
});
System.out.println();
System.out.println("Student list by name:");
System.out.println();
for(int j = 0; j < counter; j++){
System.out.println(studentArray[j]);
}
//Sort Scores
Arrays.sort(studentArray,0,counter, new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2) {
return Integer.valueOf(s2.getScore()).
compareTo(Integer.valueOf(s1.getScore()));
}
});
System.out.println();
System.out.println();
System.out.println("Student list by score:");
System.out.println();
for(int j = 0; j < counter; j++){
System.out.println(studentArray[j]);
}
//Close Scanner
aScanner.close();
}
}
static class Student implements Comparable<Student> {
//Instance Variables
private String firstName;
private String lastName;
private int score;
//Getters & Setters
public Student( String firstName, String lastName, int score ) {
this.firstName = firstName;
this.score = score;
this.lastName = lastName;
}
public int getScore() {
return score;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
//CompareTo Method
@Override
public int compareTo( Student s ) {
if( !firstName.equalsIgnoreCase( s.firstName ) ) {
return firstName.compareToIgnoreCase( s.firstName );
}
if( !lastName.equalsIgnoreCase( s.lastName ) ) {
return lastName.compareToIgnoreCase( s.lastName );
}
return (new Integer(score)).compareTo((new Integer(s.score)));
}
@Override public String toString(){ return lastName + ", "+ firstName +" : "+score; }
}
}
采纳答案by Yogendra Singh
I think you should change your last line in compareTo as below:
我认为您应该更改 compareTo 中的最后一行,如下所示:
return (new Integer(examScore)).compareTo((new Integer(s.examScore));
or
或者
return Integer.valueOf(examScore).compareTo(Integer.valueOf(s.examScore));
This will compare the two values and return accordingly.
这将比较两个值并相应地返回。
EDIT:
编辑:
Some corrections in your program:
程序中的一些更正:
Add a
toString()
method in yourStudent
class as:@Override public String toString(){ return firstName + " "+ lastName +" : "+examScore; }
Update the
main()
method in app as below:public static void main(String[] args) throws Exception { Scanner aScanner = new Scanner( new FileReader("src//chapt11//ch11AS8data.txt")); System.out.println("Welcome to the Student Scores Application.\n"); int nStudent = 100; Student[] studentArray = new Student[nStudent]; Scanner lineScanner = null; int counter = 0; while (aScanner.hasNext()) { lineScanner = new Scanner(aScanner.nextLine()); String lastName = lineScanner.next(); String firstName = lineScanner.next(); int examScore = lineScanner.nextInt(); System.out.println("Student " + counter + " " + firstName + " " + lastName + " " + +examScore); studentArray[counter++]=new Student(lastName, firstName, examScore); lineScanner.close(); } for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //sort based on first name Arrays.sort(studentArray,0,counter, new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { return s1.getFirstName().compareTo(s2.getFirstName()); } }); System.out.println("Students sorted by first name in ascending order"); for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //sort based on score Arrays.sort(studentArray,0,counter, new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { return Integer.valueOf(s1.getExamScore()). compareTo(Integer.valueOf(s2.getExamScore())); } }); System.out.println("Students sorted by score in ascending order"); for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //To compute the average: double sum = 0.0; for(int j = 0; j < counter; j++){ sum+=studentArray[j].getExamScore(); } double average = (sum*1.0)/counter; System.out.println("Average Score = "+average ); aScanner.close(); }
toString()
在您的Student
类中添加一个方法:@Override public String toString(){ return firstName + " "+ lastName +" : "+examScore; }
更新
main()
app中的方法如下:public static void main(String[] args) throws Exception { Scanner aScanner = new Scanner( new FileReader("src//chapt11//ch11AS8data.txt")); System.out.println("Welcome to the Student Scores Application.\n"); int nStudent = 100; Student[] studentArray = new Student[nStudent]; Scanner lineScanner = null; int counter = 0; while (aScanner.hasNext()) { lineScanner = new Scanner(aScanner.nextLine()); String lastName = lineScanner.next(); String firstName = lineScanner.next(); int examScore = lineScanner.nextInt(); System.out.println("Student " + counter + " " + firstName + " " + lastName + " " + +examScore); studentArray[counter++]=new Student(lastName, firstName, examScore); lineScanner.close(); } for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //sort based on first name Arrays.sort(studentArray,0,counter, new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { return s1.getFirstName().compareTo(s2.getFirstName()); } }); System.out.println("Students sorted by first name in ascending order"); for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //sort based on score Arrays.sort(studentArray,0,counter, new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { return Integer.valueOf(s1.getExamScore()). compareTo(Integer.valueOf(s2.getExamScore())); } }); System.out.println("Students sorted by score in ascending order"); for(int j = 0; j < counter; j++){ System.out.println(studentArray[j]); } //To compute the average: double sum = 0.0; for(int j = 0; j < counter; j++){ sum+=studentArray[j].getExamScore(); } double average = (sum*1.0)/counter; System.out.println("Average Score = "+average ); aScanner.close(); }
回答by Bohemian
Your mistake is in the last line of the compareTo()
method:
你的错误在方法的最后一行compareTo()
:
change
改变
return examScore = s.examScore;
to
到
return examScore - s.examScore;
You want to return a difference, not set your instance variable!
您想返回一个差异,而不是设置您的实例变量!
回答by Eddie B
Since this is homework I'm not giving you the full answer ... But here's the general idea of what you should be working towards ...
由于这是作业,我不会给你完整的答案......但这是你应该努力的总体思路......
import java.io.FileReader;
import java.util.Scanner;
public class App {
public static void main( String[] args ) throws Exception {
// TODO Auto-generated method stub
Scanner aScanner = new Scanner( new FileReader( "src/scores.txt" ) );
System.out.println( "Welcome to the Student Scores Application." );
System.out.println();
Student[] studentArray;
String lastName;
String firstName;
int examScore = 0;
double average = 0;
int nStudent = 100;
studentArray = new Student[nStudent];
int counter = 0;
while( aScanner.hasNext() ) {
lastName = aScanner.next();
firstName = aScanner.next();
examScore = aScanner.nextInt();
studentArray[counter] = new Student( lastName, firstName, examScore );
System.out.println( "Student " + studentArray[counter].getFirstName() + " " + studentArray[counter].getLastName() + "'s " + "Test Score is :" + studentArray[counter].getExamScore() );
++counter;
if( counter >= nStudent ) {
break;
}
}
}
static class Student implements Comparable<Student> {
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( Student s ) {
if( !lastName.equalsIgnoreCase( s.lastName ) ) {
return lastName.compareToIgnoreCase( s.lastName );
}
if( !firstName.equalsIgnoreCase( s.firstName ) ) {
return firstName.compareToIgnoreCase( s.firstName );
}
return examScore - s.examScore;
}
}
}