如何将学生的姓名与相应的成绩联系起来我还需要对成绩数组进行排序并让姓名保持等级 [英] How Do I Link The Names Of The Students With Their Corresponding Grades Also I Need To Sort The Grades Array And Have The Names Stay With The Grades
本文介绍了如何将学生的姓名与相应的成绩联系起来我还需要对成绩数组进行排序并让姓名保持等级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/**
* Write a description of class DoubleArray here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.*;
public class DoubleArray
{
public DoubleArray()
{
String[] names;
String[] grades;
names = new String[10];
grades = new String[10];
Scanner input = new Scanner(System.in);
for (int i=0; i < (names.length); i++) {
System.out.print("Enter a name: ");
String name = input.next();
names[i] = name;
System.out.print("Enter a grade: ");
String grade = input.next();
grades[i] = grade;
}
for (String name: names)
System.out.print(name + "\t");
for(String grade: grades)
System.out.print(grade);
Arrays.sort(grades);
System.out.print("Sorted Version");
for (String name: names)
System.out.print(name + "\t");
for(String grade: grades)
System.out.print(grade);
}
}
推荐答案
最好的方法?简单:创建一个包含Name属性和Grade属性的Student类。
[edit]
忽略下面的代码:它是在C#中,而不是Java。 :O
原则是相同的:创建一个包含两个属性的类,它们将保持步调。
[/ edit]
你所要做的就是让它实现IComparable:
The best way? Simple: create a Student class which contains a Name property and a Grade property.
[edit]
Ignore the code below this: it's in C#, not Java. :O
The principle is the same though: create a class that contains the two properties and they will stay in step.
[/edit]
All you have to do is make it implement IComparable:
public class Student : IComparable
{
public string Name { get; set; }
public string Grade { get; set; }
public int CompareTo(object obj)
{
return Name.CompareTo(((Student) obj).Name);
}
public override string ToString()
{
return string.Format("{0}, Grade {1}", Name, Grade);
}
}
它将排序:
And it will sort:
Student[] students = new Student[3];
students[0] = new Student() { Name = "Joe", Grade = "A" };
students[1] = new Student() { Name = "Aaron", Grade = "F" };
students[2] = new Student() { Name = "Barry", Grade = "B" };
Array.Sort(students);
有人可以在java中显示此代码。
Could someone please display this code in java.
这篇关于如何将学生的姓名与相应的成绩联系起来我还需要对成绩数组进行排序并让姓名保持等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文