0

Print a txt file in alphabetical order and count words

well, im starting to programming and i wanna print a txt file ordered and counting all the words inside: like ( hello i have one orange and i have one apple-> apple 1/and 1/ have 2/ hello 1/ i 2/one 2/orange 1/) how could i make this? my code only prints the text and nothing else. String camino="path to txt file"; FileReader fr = new FileReader(camino+"TM.txt"); BufferedReader br = new BufferedReader(fr); int n; int mida=0; String s = br.readLine(); // reads a single line while(s!=null) { String[] t=s.split("\\s"); // split by spaces and generates an array of Strings -words- for(int i=0;i<t.length;i++){ System.out.println(t[i]); } s = br.readLine(); } br.close(); } }

1st Jun 2017, 9:01 AM
carlos nuñez
carlos nuñez - avatar
2 Antworten
0
import java.util.Arrays; After splitting your array, sort it. Arrays.sort(t); add a variable to keep track of the number. change System.out.println to something like number++; stringNumber=number.toString(); System.out.print(t[i]); System.out.println(" " + stringNumber + "/"); That would work. I'm not sure the exact method off the top of my head to convert number to string, but printing your word with print instead of println would keep the next item on same line. the I would print the number with println to end the line. This is a pretty basic concept compared to opening and reading files. Safe to assume you didn't write this code?
1st Jun 2017, 10:24 AM
LordHill
LordHill - avatar
0
Consider this code... import java.util.Arrays; int number=0; String a="zoo apple pig pie"; String[] t=a.split("\\s"); Arrays.sort(t); for(int i=0;i<t.length;i++){ number++; String strNumber=Integer.toString(number); System.out.print(t[i]); System.out.println(" " + strNumber + "/"); } output: apple 1/ pie 2/ pig 3/ zoo 4/
1st Jun 2017, 11:26 AM
LordHill
LordHill - avatar