国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java使用Comparable解決排序問題

2019-11-26 15:10:22
字體:
供稿:網(wǎng)友

本文實例講述了Java使用Comparable解決排序問題的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

一次舉重競賽的比賽規(guī)則是:選手的成績以成功舉起的總重量來排序,舉起總重量多的排在前面;當(dāng)舉起總重量相同時,按照體重來排序,體重輕的排在前面;要求程序讀取數(shù)據(jù)文件作為輸入,并按照上述規(guī)則排序后,打印出選手編號;數(shù)據(jù)文件說明如下:現(xiàn)有5名選手,其選手編號、成功舉起的總重量及其體重如數(shù)據(jù)文件data4.txt,樣例內(nèi)容為:

<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>

首先我要解決的是文件解析的問題:

如何把文件內(nèi)容解析成想要的數(shù)據(jù):即提取出每個選手的編號,成績和體重
我用一個實體Person來封裝這些屬性

整體代碼:

import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;public class forth {public static void main(String[] args) {ArrayList<Person> list=new ArrayList<Person>();try {FileReader fr=new FileReader("c://data.txt");BufferedReader br=new BufferedReader(fr);String str=null;int num=0;int score=0;int weight=0;int i=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++;Person p=new Person(num,score,weight);list.add(p);  }  else   continue;}} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}Person[] plist=new Person[list.size()];list.toArray(plist);Arrays.sort(plist);for(int i=0;i<plist.length;i++){System.out.print(plist[i].getNum()+". " +plist[i].getScore()+" "+plist[i].getWeight()+"/n/r");}}}class Person implements Comparable<Person>{private int num;private int weight;private int score;public Person(int num,int score,int weight){this.num=num;this.score=score;this.weight=weight;}@Overridepublic int compareTo(Person other) {if(this.score>other.score)return -1;  else if(this.score<other.score) return 1;  else  return this.weight>other.weight?1:-1;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public int getWeight() {return weight;}public void setWeight(int weight) {this.weight = weight;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}}

希望本文所述對大家的java程序設(shè)計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 四子王旗| 翼城县| 宝山区| 兖州市| 山阳县| 定结县| 木里| 榕江县| 工布江达县| 明水县| 措勤县| 牟定县| 大埔区| 双城市| 大石桥市| 虎林市| 金湖县| 象山县| 昌图县| 高淳县| 吐鲁番市| 留坝县| 伊川县| 宜宾市| 临西县| 三门县| 宁津县| 拜城县| 彰武县| 太白县| 民乐县| 新乡市| 集贤县| 奉贤区| 突泉县| 富蕴县| 炎陵县| 马公市| 密山市| 丹阳市| 大连市|