I have a Method i used to extract info from a website and have it currently going to TXT files. I am looking to sort the information out similar to how it is displayed in the output when I do a print statement to show results as shown below:
QB 3 Anderson, Derek ACT TDS -- INT -- YDS -- RTG 0.0 CAR
QB 2 Barkley, Matt ACT TDS 0 INT 4 YDS 300 RTG 44.6 PHI
QB 5 Bethel-Thompson, McLeod ACT TDS 0 INT 0 YDS 0 RTG 0.0 SF
In my text file I have it shown as:
QB3Anderson, DerekACTTDS--INT--YDS--RTG0.0CARQB2Barkley, MattACTTDS0INT4YDS300RTG44.6PHIQB5Bethel-Thompson, McLeodACTTDS0INT0YDS0RTG0.0SF
Any Suggestions (Please note this is in Java)
Read each line using a BufferedReader. Each line will be a string. Then add each line to a list and sort the list.
BufferedReader reader = new BufferedReader(new FileReader("text.txt"));
String line;
ArrayList<Entry> list = new ArrayList<Entry>();
while((line = reader.readLine()) != null) {
list.add(new Entry(line));
}
Collections.sort(list);
// list is sorted!
Then you need the Entry class:
import java.util.StringTokenizer;
public class Entry implements Comparable<Entry> {
private String qb;
private String number;
private String name;
public Entry(String text) {
StringTokenizer st = new StringTokenizer("", " ");
this.qb = st.nextToken();
this.number = st.nextToken();
this.name = st.nextToken();
// ... etc
}
@Override
public int compareTo(Entry other) {
return this.name.compareTo(other.name);
}
}
Your class needs to implement Comparable so that Collections.sort() will know how to sort. Also, implementing equals() and hashCode() is always a good idea.
It seems to me your problem is really about parsing and formatting rather than sorting?
To format text like this you could use a Scanner to easily match each QB like this
String text = "QB3Anderson, DerekACTTDS--INT--YDS--RTG0.0CARQB2Barkley, MattACTTDS0INT4YDS300RTG44.6PHIQB5Bethel-Thompson, McLeodACTTDS0INT0YDS0RTG0.0SF";
Scanner scanner = new Scanner(text);
scanner.useDelimiter("QB");
while(scanner.hasNext()){
String qb = "QB" + scanner.next();
System.out.println(qb);
}
which will output:
QB3Anderson, DerekACTTDS--INT--YDS--RTG0.0CAR
QB2Barkley, MattACTTDS0INT4YDS300RTG44.6PHI
QB5Bethel-Thompson, McLeodACTTDS0INT0YDS0RTG0.0SF
Then for each qb string you could use String.subString() and String.indexOf() to do simple pattern matches on the fields you want eg.
String number = qb.substring(2, 3);
String name = qb.substring(3, qb.indexOf("ACT"));
String INT = qb.substring(qb.indexOf("INT") + 3, qb.indexOf("YDS") );
Once you have all your fields parsed then print them in the format and order you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.