The example of this article tells the way Java uses comparable to solve sorting problems. Share it for everyone for your reference. The specific implementation method is as follows:
The rules of the competition of one weightlifting competition are: the players' results are sorted by the total weight of the successful lift, and the total weight is ranked in front. When the total weight is the same, sort according to the weight of the same weight. ; Requires the program to read the data file as the input, and after the above rules are sorted, the player number is printed; .txt, the content of the sample is:
<p> <no> 1 </no> <lw> 140 </lw> <bw> 54 </b> <p> <no> 2 </no> <lw> 155 </lw>> <bw> 53 </bw> </p> <no> 3 </no> <lw> 140 </lw> <bw> 42 </b> <p> <no> 4 </no> <lw> 140 </lw> <bw> 55 </b> </p> <no> 5 </no> <lw> 130 </lw> <bw> 46 </bw > </p>
First of all, what I want to solve is the problem of file analysis:
How to analyze the content of the file into the desired data: that is, extract the number of each player, the grades and weight, I use a physical figure to pack these attributes
Overall code:
Import java.io.BuffRedReader; Import Java.filenotFoundexception; Import Java.io.filerereader; Import Java.io.ioException; Import raylist; 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"); dream (fr); string str = null; int num = 0; int screen = 0; int weight = 0; int i = 0; space ((str = BR.Readline ())! = NULL) {i ++; if (i%5 == 2 2 ) {str = str.trim (). substring (4, str.Length () -5); num = Integer.parseint (str); str = <) 4, str.Length () -5); score = Integer.parseint (str); i ++; str = BR.Readline (). Trim (); str = str.substring (4, str.Length ()) ; Weight = Integer.parseint (str); I ++; Person P = New Person (NUM, SCORE, Weight); list.adddd (p);} Else Continue;} Catch ) {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; ght) {this.num = num; this .score = score; this.weight = weight;}@osone. THER.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 tweight () {Return Weight;} Public Void Setweight (int weight) {this.weight = weight;} public int Getscore () {Return score;} Public void setscore (int screen) {This.SC ol = score;}}It is hoped that this article is helpful to everyone's Java program design.