My code give me an index out of bounds because the index = 0 and size = 0 how can i fix this? Basically what this code should do is find the frequency of the letters in the string and add them all up together in the arraylist. the array list is in alphabetical order so at 0 it would represent the frequency for the letter a...
import java.io.*;
import java.util.*;
public class Encoding {
ArrayList<Integer> frequency;
public void frequency(String fileName) {
frequency = new ArrayList<Integer>();
try {
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNextLine()){
String line = scan.nextLine();
Scanner token = new Scanner (line);
while(token.hasNext()){
String s = token.next();
countLettersInString(s);
}
}
System.out.println(frequency);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void countLettersInString(String s) {
int count = 0;
int position = 0;
s = s.toLowerCase();
for (char i = 'a'; i <= 'z'; i++) {
count = 0;
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if (c == i)
count++;
}
int oldCount = frequency.get(position);
frequency.add(position, oldCount+count);
position++;
}
}
}