So basically i'm trying to write a code that will count the amount of times a letter appears in a text file.
I've got most of the code down, and as far I know it should work. However, I can not figure out how to display
the count, there is a precision error, and i'm guessing it has to do with the part where i try to use a char where or an int should be or vice versa. I am reusing code that I wrote for a different project that used a char array,
this one uses an int array to do it, which explains the precision error, but i do not know how to convert the code to work for an int array. i've tried switching int to char, but that doesn't work.
I've got most of the code down, and as far I know it should work. However, I can not figure out how to display
the count, there is a precision error, and i'm guessing it has to do with the part where i try to use a char where or an int should be or vice versa. I am reusing code that I wrote for a different project that used a char array,
this one uses an int array to do it, which explains the precision error, but i do not know how to convert the code to work for an int array. i've tried switching int to char, but that doesn't work.
import java.io.*;
import java.util.*;
import java.io.IOException;
public class SchardinA02 {
public static void main(String [] args) {
int[] counter = new int[26];
char c = 0;
int buf = -1;
Reader in = null;
try {
System.out.println("Count of each letter found in " + "input.txt" + ":");
System.out.println("");
in = new FileReader("input.txt");
while((buf = in.read()) > -1) {
c = (char) buf;
c = Character.toLowerCase(c);
if (Character.isLetter(c)) {
counter [c -'a']++;
}
}
//-------------------------------------------------------------
System.out.println("Count of each letter found in input.txt: " );
Arrays.sort(counter);
for (int addUp = 0; addUp < counter.length; addUp++) {
char ch = counter[addUp];
int count = 0;
for (int i = 0; i < counter.length; i++) {
if (ch == counter[i])
count++;
}//first nested for loop
boolean flag = false;
for (int j = addUp - 1; j >= 0; j--) {
if (ch == counter[j])
flag = true;
}//second nested for loop
if (!flag) {
System.out.println(ch + ":" + count);
}//if statement
}//Main for loop
System.out.println("Total letters found: "+ counter.length );
//------------------------------------------------------
}catch (IOException e) {
System.out.println("Could not read from file: " + e.getMessage());
}
}
}