黑马程序员技术交流社区
标题:
数组排序问题
[打印本页]
作者:
陈少文
时间:
2012-6-10 00:01
标题:
数组排序问题
已知表如下
姓名 年龄 得分
陈一, 27 , 79.0
陈二, 23 , 74.0
陈三, 26 , 88.0
陈四, 28 , 85.0
陈三, 26 , 88.0
求跟据得分,进行排序
也就是要得到
陈二, 23, 74.0
陈一, 27 , 79.0
陈四, 28 , 85.0
陈三, 26 , 88.0
陈三, 26 , 88.0
这是自己写的代码
class Test
{
private String name;
private int age;
private double score;
Test(String name,int age,double score)
{
this.name = name;
this.age = age;
this.score = score;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getScore()
{
return score;
}
//排序
public static void order(double [] arr)
{
for(int x =0;x<arr.length-1;x++)
{
for(int y = x+1;y<arr.length;y++)
{
if(arr[x]>arr[y])
{
//定义一个第三方变量换位
double temp = arr[x];
arr[x] =arr[y];
arr[y]=temp;
}
}
}
}
}
class Var
{
public static void main(String[] args)
{
//创建5个对象
Test s1 = new Test("陈一",27,75);
Test s2 = new Test("陈二",28,88);
Test s3 = new Test("陈三",26,84);
Test s4 = new Test("陈四",25,91);
Test s5 = new Test("陈五",23,79);
//把分数,放入一个数组
double[] arr = {s1.getScore(),s2.getScore(),s3.getScore(),s4.getScore(),s5.getScore()};
//将分数进行排序
s1.order(arr);
//用编历方法打印
for(int a = 0;a<arr.length;a++)
{
if(arr[a]== s1.getScore())
System.out.println(s1.getName()+","+s1.getAge()+","+s1.getScore());
else if(arr[a]==s2.getScore())
System.out.println(s2.getName()+","+s2.getAge()+","+s2.getScore());
else if(arr[a]==s3.getScore())
System.out.println(s3.getName()+","+s3.getAge()+","+s3.getScore());
else if(arr[a]==s4.getScore())
System.out.println(s4.getName()+","+s4.getAge()+","+s4.getScore());
else if(arr[a]==s5.getScore())
System.out.println(s5.getName()+","+s5.getAge()+","+s5.getScore());
}
}
}
代码感觉写的很傻,请问一下兄弟们有没有其它思路。如果我有一批这样的数据那如何进行排序
作者:
赵兵锋
时间:
2012-6-10 00:17
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class Main{
public static void main(String[] args) {
ArrayList<Stu> list = new ArrayList<Stu>();
list.add(new Stu("陈一",27,79.0));
list.add(new Stu("陈二",23,74.0));
list.add(new Stu("陈三",26,88.0));
list.add(new Stu("陈四",28,85.0));
list.add(new Stu("陈三",26,88.0));
Stu[] arr = new Stu[list.size()];
list.toArray(arr);
Arrays.sort(arr, new Comparator<Stu>(){
@Override
public int compare(Stu o1, Stu o2) {
if(o1.getScore()<o2.getScore()){
return -1;
}else if(o1.getScore()==o2.getScore()){
return 0;
}else{
return 1;
}
}
});
for(Stu s:arr){
System.out.println(s);
}
}
}
class Stu{
private String name;
private int age;
private double score;
public Stu(String name,int age,double score){
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return name+":"+age+","+score;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2