有关java的排序的问题
比如说输入n组学生的能力跟成绩先按能力排序,若能力排序再按成绩排序请问这一类的问题应该怎么写程序?...
比如说输入n组学生的能力跟成绩
先按能力排序,若能力排序再按成绩排序
请问这一类的问题应该怎么写程序? 展开
先按能力排序,若能力排序再按成绩排序
请问这一类的问题应该怎么写程序? 展开
2个回答
展开全部
package zhidao;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Student
{
private int power;
private double score;
public Student ( int power, double score )
{
this.power = power;
this.score = score;
}
public String displays ()
{
StringBuilder builder = new StringBuilder ();
builder.append ("Student [power=");
builder.append (power);
builder.append (", score=");
builder.append (score);
builder.append ("]");
return builder.toString ();
}
public void setScore ( double score )
{
this.score = score;
}
public double getScore ()
{
return score;
}
public static void main ( String[] args )
{
System.out.print ("建立一个含有n个学生的数组, 从键盘输入n: ");
Scanner scanner = new Scanner (System.in);
int count = 0;
int n = scanner.nextInt ();
Student[] students = new Student[n];
System.out.println ("从键盘输入每个学生的信息: 能力、成绩 用英文逗号分隔.");
String line = null;
while (count < n && null != ( line = scanner.next () ))
{
if (line.matches ("^\\d+\\,\\d+(\\.\\d*)?$"))
{
int power = Integer.parseInt (line.split ("\\,")[0].trim ());
double score = Double.parseDouble (line.split ("\\,")[1].trim ());
students[count] = new Student (power, score);
count++;
}
}
scanner.close ();
System.out.println ("排序:");
Arrays.sort (students, new Comparator<Student> ()
{
@Override
public int compare ( Student o1, Student o2 )
{
if (o1.power > o2.power)
{
if (o1.score > o2.score)
{
return 1;
}
else if (o1.score < o2.score)
{
return -1;
}
else
{
return 1;
}
}
else if (o1.power < o2.power)
{
if (o1.score < o2.score)
{
return 1;
}
else if (o1.score > o2.score)
{
return -1;
}
else
{
return -1;
}
}
else
{
if (o1.score > o2.score)
{
return 1;
}
else if (o1.score < o2.score)
{
return -1;
}
else
{
return 0;
}
}
}
});
for ( Student student : students )
{
System.out.println (student.displays ());
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询