So I am having trouble with the the following question in regards to counting th
ID: 3539047 • Letter: S
Question
So I am having trouble with the the following question in regards to counting the number of occurances of characters in two files. I am able to count the number of words but I am not able to count the number of characters. For example (a=27, b=42 ....) The exact question posed is: "Write a character counting method public static Map<Character, Integer> getCounts(FileInputStream input) that creates a Map of character counts in a file. Report the three most common alphabetic characters (a-z) and their counts in each file (moby and hamlet)." and next is the code I have. I am also unsure how to use the (FileInputStream) that is mentioned as a parameter. Thank you in advance for the help. and am willing to show more of my code if it is needed.
(This is the code from the book for counting number or words. I need to adjust it to count the number of characters also using FileInputStream as parameter)
public static Map<Character, Integer> getCounts(FileInputStream input) {
Map<Character, Integer> charCounts = new TreeMap<Character, Integer>();
while (input.hasNext()) {
String word = input.next().toLowerCase();
if (charCounts.containsKey(word)) {
int count = charCounts.get(word);
charCounts.put(word, count +1);
} else {
charCounts.put(word, 1);
}
}
return charCounts;
}
Explanation / Answer
public static Map<Character, Integer> getCounts(FileInputStream input) {
Map<Character, Integer> charCounts = new TreeMap<Character, Integer>();
Scanner scanner = new Scanner(input);
while (input.hasNextLine()) {
String word = input.nextLine();
char ch;
for(int i=0; i<word.length; i++)
{
ch = word.charAt(i);
if (charCounts.containsKey(ch))
{
int count = charCounts.get(ch);
charCounts.put(ch, count+1);
} else
{
charCounts.put(ch, 1);
}
}
}
return charCounts;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.