Question & Answer: Java – Design a program that reads in an ASCII text file (provided) and creates an output file that contain…..

Java – Design a program that reads in an ASCII text file (provided) and creates an output file that contains each unique character and the number of time the character appears in the file. Do not sort the output. Each unique character in the file must be represented by a character frequency class instance. For this exercise, the character frequency objects must be stored in a Linked List. Read the input file character-by-character. Reading the entire file into memory is prohibited.   Needs to use CharacterFrequency class   variables ch : char, frequency : int and methods +getCharacter() : char +setCharacter(character : char) +getFrequency() : int +setFrequency(frequency : int) +increment() +Equals() : bool +ToString() : string. Any help with Java code for this exercise would be appreciated.

For example, given the sample input file:
Hello.

The output file would look like this:

H(72) = 1

e(101) = 1

l(108) = 2

o(111) = 1

.(46) = 1

Expert Answer

 

public class CountLetters
{
public static void main(String[] args) throws IOException
{
Map<Character, Integer> characters = new TreeMap<Character, Integer>();
Scanner scanner = null;

try {
scanner = new Scanner(new File(“C:/text.txt”),”utf-8″);

while (scanner.hasNext())
{
char[] line = scanner.nextLine().toLowerCase().toCharArray();

for (Character character : line)
{
if (Character.isLetter(character))
{
if (characters.containsKey(character))
{
characters.put(character, characters.get(character) + 1);
} else
{
characters.put(character, 1);
}
}
}
}
}
finally
{
if (scanner != null)
{
scanner.close();
}
}

if (!characters.isEmpty())
{
for (Map.Entry<Character, Integer> entry : characters.entrySet())
{
System.out.println(entry.getKey() + “: ” + entry.getValue());
}
}
}
}

Still stressed from student homework?
Get quality assistance from academic writers!