Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have some errors in my code saying HuffmanCode.java:8: error: type PriorityQueue does not take parameters PriorityQueue trees = new PriorityQueue (); Below is my

I have some errors in my code saying

HuffmanCode.java:8: error: type PriorityQueue does not take parameters PriorityQueue trees = new PriorityQueue();

Below is my code:

import java.util.*;

public class HuffmanCode { // input is an array of frequencies, indexed by character code public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue trees = new PriorityQueue(); // initially, we have a forest of leaves // one for each non-empty character for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; // loop until there is only one tree left while (trees.size() > 1) { // two trees with least frequency HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); // put into new node and re-insert into queue trees.offer(new HuffmanNode(a, b)); } return trees.poll(); } public static void printCodes(HuffmanTree tree, StringBuffer prefix) { assert tree != null; if (tree instanceof HuffmanLeaf) { HuffmanLeaf leaf = (HuffmanLeaf)tree; // print out character, frequency, and code for this leaf (which is just the prefix) System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; // traverse left prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); // traverse right prefix.append('1'); printCodes(node.right, prefix); prefix.deleteCharAt(prefix.length()-1); } } public static void main(String[] args) { String test = ""; Scanner scan = new Scanner(System.in); System.out.println("Enter a string of letters to test: "); test = scan.nextLine(); // we will assume that all our characters will have // code less than 256, for simplicity int[] charFreqs = new int[256]; // read each character and record the frequencies for (char c : test.toCharArray()) charFreqs[c]++; // build tree HuffmanTree tree = buildTree(charFreqs); // print out results System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Concepts of Database Management

Authors: Philip J. Pratt, Mary Z. Last

8th edition

1285427106, 978-1285427102

More Books

Students also viewed these Databases questions

Question

Why do HCMSs exist? Do they change over time?

Answered: 1 week ago