Hello, I've had a good search to see if anything else was posted in relevance with this, but can't find anything that suits my exact needs.
I've been given a Java assignment to take in a file, and read how many characters it has (omitting white-space and new lines) and then to display the top ten most occurring characters.
Now, I can display how many characters, and how many of each character appears, but I'm finding it difficult to display only the top 10 and in descending order (the one occurring most frequently to the least frequently occurring one)
Here's what I have so far.
mport java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class FrequencyAgain {
public static void main(String[] args) throws Exception {
//Set up file to be read in.
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Dave/Desktop/myfile.txt"));
//Set up attributes
String strLine = "";
String str = "";
//Set true if character case if not an issue.
Boolean charCase = false;
//Join strings together, ommitting returns and new lines.
while ((strLine = br.readLine()) != null) {str += strLine;}
//Remove whitespace so characters can be counted.
String st = str.replaceAll(" ", "");
//Changes to lowercase if character case is insensitive.
if(charCase == true) {
st = st.toLowerCase();
}
//assign letters to array
char[] letters = st.toCharArray();
//Print out total letters and occurance of each letter
System.out.println("Total Characters: " + st.length());
System.out.println("Character Total");
//Cycle through each letter
for(int counter = 0; counter < letters.length; counter++) {
char character = letters[counter];
int count = 0;
//Counter for letters and how often they occur.
for(int i = 0; i < letters.length; i++) {
if(character == letters[i]) {
count++;}
}
boolean flag = false;
for (int j = counter - 1; j >= 0; j--) {
if (character == letters[j]){
flag = true;}
}
if (!flag) {
System.out.println(character + " (" + count + ')');}
}
}
}
Thanks for anyone's help in advance! :)