Please help me with this problem. I'm trying to write a code that read a .txt file and then it would count the frequencies of each letter in the file. This is what I came up with :
public static void charCount(String file) throws IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int[] count = new int[26];
String line;
while ((line = br.readLine()) != null) {
line = line.toUpperCase();
char[] characters = line.toCharArray();
for (int i = 0; i < line.length(); i++) {
if ((characters[i] >='A') && (characters[i] <='Z')) {
count[characters[i] - 'A']++;
}
}
}
File file2 = new File("D:/Project/Aufgabe/Winter_2019/frequency.txt");
file2.createNewFile();
FileWriter fw = new FileWriter(file2);
for (int i = 0; i < 26; i++) {
fw.write(((char)(i + 'A')) + ": " + count[i]);
}
fw.close();
br.close();
}
When I tried to print the result in the console with System.out.println(), it gives out these results:
A: 15
B: 4
C: 9
D: 10
E: 2
F: 1
G: 0
H: 3
I: 5
J: 6
K: 3
L: 0
M: 2
N: 7
O: 3
P: 1
Q: 1
R: 0
S: 4
T: 0
U: 2
V: 0
W: 5
X: 0
Y: 1
Z: 0
Which is what I want. But when I tried to write it in a file, it gives it these results in the .txt file:
㩁ㄠ䈵›䌴›䐹›〱㩅㈠㩆ㄠ㩇〠㩈㌠㩉㔠㩊㘠㩋㌠㩌〠㩍㈠㩎㜠㩏㌠㩐ㄠ㩑ㄠ㩒〠㩓㐠㩔〠㩕㈠㩖〠㩗㔠㩘〠㩙ㄠ㩚〠
I'm still new to java, so a help would be much appreciated.