Java使用Comparable解决排序问题
本文实例讲述了Java使用Comparable解决排序问题的方法。分享给大家供大家参考。具体实现方法如下:
一次举重竞赛的比赛规则是:选手的成绩以成功举起的总重量来排序,举起总重量多的排在前面;当举起总重量相同时,按照体重来排序,体重轻的排在前面;要求程序读取数据文件作为输入,并按照上述规则排序后,打印出选手编号;数据文件说明如下:现有5名选手,其选手编号、成功举起的总重量及其体重如数据文件data4.txt,样例内容为:
<p> <no>1</no> <lw>140</lw> <bw>54</bw> </p> <p> <no>2</no> <lw>155</lw> <bw>53</bw> </p> <p> <no>3</no> <lw>140</lw> <bw>42</bw> </p> <p> <no>4</no> <lw>140</lw> <bw>55</bw> </p> <p> <no>5</no> <lw>130</lw> <bw>46</bw> </p>
首先我要解决的是文件解析的问题:
如何把文件内容解析成想要的数据:即提取出每个选手的编号,成绩和体重
我用一个实体Person来封装这些属性
整体代码:
importjava.io.BufferedReader;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.Arrays;
publicclassforth{
publicstaticvoidmain(String[]args){
ArrayList<Person>list=newArrayList<Person>();
try{
FileReaderfr=newFileReader("c:\\data.txt");
BufferedReaderbr=newBufferedReader(fr);
Stringstr=null;
intnum=0;
intscore=0;
intweight=0;
inti=0;
while((str=br.readLine())!=null)
{
i++;
if(i%5==2)
{
str=str.trim().substring(4,str.length()-5);
num=Integer.parseInt(str);
str=br.readLine().trim();
str=str.substring(4,str.length()-5);
score=Integer.parseInt(str);
i++;
str=br.readLine().trim();
str=str.substring(4,str.length()-5);
weight=Integer.parseInt(str);
i++;
Personp=newPerson(num,score,weight);
list.add(p);
}
else
continue;
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
catch(IOExceptione){
e.printStackTrace();
}
Person[]plist=newPerson[list.size()];
list.toArray(plist);
Arrays.sort(plist);
for(inti=0;i<plist.length;i++)
{
System.out.print(plist[i].getNum()+"."+plist[i].getScore()+""+plist[i].getWeight()+"\n\r");
}
}
}
classPersonimplementsComparable<Person>{
privateintnum;
privateintweight;
privateintscore;
publicPerson(intnum,intscore,intweight){
this.num=num;
this.score=score;
this.weight=weight;
}
@Override
publicintcompareTo(Personother){
if(this.score>other.score)return-1;
elseif(this.score<other.score)return1;
else
returnthis.weight>other.weight?1:-1;
}
publicintgetNum(){
returnnum;
}
publicvoidsetNum(intnum){
this.num=num;
}
publicintgetWeight(){
returnweight;
}
publicvoidsetWeight(intweight){
this.weight=weight;
}
publicintgetScore(){
returnscore;
}
publicvoidsetScore(intscore){
this.score=score;
}
}
希望本文所述对大家的java程序设计有所帮助。