I am getting a null pointer exception and I don't know why. This program is supposed to build a huffman tree. I get a sentence and get the frequencies and make nodes out of them in the Freq() function. I prioritize them from smallest to largest with the prioritizeQueue() function. Then I build a tree with the build tree function. The problem I beleive is in the buildtree function. I don't know.
import java.util.StringTokenizer;
import java.util.*;
publicclass HuffmanTree
{
//Some class variables.
Stack Queue=new Stack();
Stack temp=new Stack();
int row=0, col=0;
treeNode root;
public HuffmanTree(String sentence){
Freq(sentence, 0);
Queue=prioritizeQueue(Queue);
root=buildTree(Queue);
//System.out.print("This is the root: ");
//root.printNode();
}
//The treeNode innner class.
publicclass treeNode
{
int frequency;
String val;
treeNode r;//child
treeNode l;//child
public treeNode(String value, int freq, treeNode right, treeNode left)
{
this.frequency=freq;
this.val=value;
this.r=right;
this.l=left;
}
publicvoid printNode(){
System.out.println("["+val+"|"+frequency+"]");
}
}
/*****************************************************
Name: Freq()
Parameters: String, int
Declared variables:char current, bool doIt, int freqCount
char fc.
Return value: void
Purpose: Takes a String argument, calculates the frequencies
of the characters in the String, creates nodes for them
and inserts them into a Queue.
Algorithm: (assumes the user puts all the characters in the same case)
Freq(entireString, starting indx 'initialy starts at 0')
remove white spaces if flag alows.
frequent count=0
current=char @ stIndx
for(compare every char in the entire string to char @ stIndx)
every true comparison to the char @ stIndx add one to a
counter for that char.
end for.
create a new treeNode
push it onto the Queue.
remove every instance of the current char.
set white space flag to true
if(startIndx is not at the end of the string)
recurse.
end.
****************************************************/
publicvoid Freq(String s, int stIndx){
char current;
boolean doIt=true;
treeNode node1;
if(doIt){
s=removeWhiteSpaces(s);
doIt=false;
}
int freqCount=0;
current=s.charAt(stIndx);
for(int i=0; i<s.length(); ++i){
if(current==s.charAt(i))
freqCount++;//Number of character accurances.
}
String x = String.valueOf(current);//Converts char-to-String.
node1=new treeNode(x,freqCount, null, null);
Queue.push(node1);
s=removeChar(s,current);//Removes every instance of the current char from sentence.
doIt=true;//Remove all the white spaces again.
if(stIndx < s.length())//If not at the end
Freq(s, stIndx);//Recurse.
}
publicvoid printQueue(Stack q){
Iterator i=q.iterator();
while(i.hasNext()){
((treeNode)i.next()).printNode();
}
}
/****************************************************
Name: prioritizeQueue()
Parameters: Stack queue
Declared variables:
Return value:void
Purpose: Takes a queue argument orders that queue and
sticks it back into the queue in priority order.
Algorithm:
prioritizeQueue(Stack q)
if(there is nothing in the Queue)
return.
new temporary Stack.
new iterator.
while (Queue has items in it)
find the highest priority node in the Queue
currentNode =highest priority node.
end while
push current node onto the temp stack
remove it from the Queue.
recurse.
*****************************************************/
public Stack prioritizeQueue(Stack q){
Iterator i=q.iterator();
int currentHigh;
treeNode currentNode, finalNode;
currentNode=(treeNode)i.next();//This is the current node to compare to the currentHigh.
currentHigh= currentNode.frequency;//This is just the int frequency.
finalNode=currentNode;
while(i.hasNext()){
currentNode=(treeNode)i.next();
if(currentHigh < currentNode.frequency){
currentHigh=currentNode.frequency;
finalNode=currentNode;
}
}
temp.push(finalNode);
q.remove(finalNode);
if(q.isEmpty()){//If I have taken the last thing out.
q=temp;
temp=null;
return q;//Quit the function.
}
else{
return prioritizeQueue(q);
}
}
/****************************************************
Name: buildTree()
Parameters: Stack q
Declared variables:
Return value:
Purpose: To take a Queue in and create a binary tree
from the nodes in the Queue.
Algorithm:
buildTree()
get two nodes out of the Queue
add the frequencies and create a parent node. (first from Q is right child)
put new parent node onto the Queue.
recurse.
end.
*****************************************************/
public treeNode buildTree(Stack q){
treeNode n1;
treeNode n2;
treeNode newParent;
if(q.size() == 1){// stop when only one item in tree
return (treeNode)q.pop();
}
n1=(treeNode)Queue.pop();//right node
System.out.println("node1 pop: ");n1.printNode();
n2=(treeNode)Queue.pop();//left node
System.out.println("node2 pop: ");n2.printNode();
//Creating a parent node, from the two nodes I popped.
newParent=new treeNode("*", n1.frequency+n2.frequency, n1, n2);
q.push(newParent);
q=prioritizeQueue(q);
return buildTree(q);//Recurse.
}
/*****************************************************
Name: removeWhiteSpaces()
Parameters: String s
Declared variables: StringTokenizer, StringBuffer
Return value: String
Purpose: Takes all the white spaces out of the specified
String object.
****************************************************/
public String removeWhiteSpaces(String s){
StringTokenizer sToken=new StringTokenizer(s," ",false);
StringBuffer sbuff=new StringBuffer();
while(sToken.hasMoreTokens()){
sbuff.append(sToken.nextToken());
}
s=sbuff.toString();//Converts the StringBuffer sbuff into a regular String.
return s;
}
/*****************************************************
Name: removeChar()
Parameters: String s, char c
Declared variables: String
Return value: String
Purpose: Removes all the characters that match the
specified 'char c' from the specified 'String s'.
****************************************************/
public String removeChar(String s, char c) {
String r = "";
for (int i = 0; i <s.length(); i ++) {
if (s.charAt(i) != c) r += s.charAt(i);
}
return r;
}
publicstaticvoid main(String[] args){
HuffmanTree tree=new HuffmanTree("susie says it is easy");
}
}
In the prioritizeQueue method you are trying to copy the objects with 'q = temp'. Thats not possible. You end up copying only references. Since 'temp=null' in the next line, q also points to null. Try
q=(Stack)temp.clone();
temp.clear();
As an afterthought, in buildTree(Stack) method, shouldn't Queue.pop() be replaced with q.pop(). I'm not sure though.
Hi, I just registered on this site today. I am creating a spam filter programme which uses genetic algorithms but I am getting a null pointer exception. Can anyone help me out with this?
Here is the code and the error message:
public class EmailChromosome {
// Private instance variables for the EmailChromosome objects
public List chromo; private Random ePopn = new Random(); private EmailElement ele; private EmailPattern pat; private EmailOperator op; public Hashtable spamNamesLUT; public Hashtable spamSubjLUT; public Hashtable spamBodLUT; public int nextIndex = 0; public double[] confiVals1 = new double[3]; public double[] confiVals2 = new double[3]; public double[] confiVals3 = new double[3]; private List child1; private List child2; private int i = 0;
/** * Constructs a single chromosome, chromo using a List. Each chromosome consists of * 18 objects. There will be six sets of the three objects: an element, a pattern * and an operator. The type of pattern and operator will be randomnly chosen from * the legal list. The elements added to the list will always be in order so that * the chromosome remains legal after all the operations carried out on it. * */ public EmailChromosome() { while(i != 18) { // Initialisation of Element, Pattern and Operator objects
ele = new EmailElement(); pat = new EmailPattern(); op = new EmailOperator();
// The elements in the chromosome will always be in the following order: // from, to, Cc, BCc, subject and body. The elements will not be randomnly // chosen in order for the chromosome to remain legal.
ele.setFromFd('f'); char o = ele.getFromFd(); Character ch = new Character(o); chromo.add(i, ch); // LINE 74 i++; // Randomn choice of the pattern which will be alongside the // "From" element. This pattern will essentially be a name chosen // randonly from the spamNames LUT. pat = selectCorrPat(ele);
chromo.add(i, pat); i++; addOp(i);
i++; ele.setToFd('t'); chromo.add(i, ele);
// The pattern after the "To" element will essentially be my name.
// Randomn choice of the pattern which will be alongside the // "Carbon Copy Field" element. This pattern will essentially be a name.
pat = selectCorrPat(ele); i++; chromo.add(i, pat); i++; addOp(i);
ele.setBCcFd('b'); i++; chromo.add(i, ele);
pat = selectCorrPat(ele); i++; chromo.add(i, pat); i++; addOp(i);
ele.setSubFd('s'); i++; chromo.add(i, ele);
// Randomn choice of the pattern which will be alongside the // "Subject Field" element. This pattern will essentially be a // spam subject chosen from the spam subjects LUT.
pat = selectCorrPat(ele); i++; chromo.add(i, pat); i++; addOp(i);
ele.setBodFd('B'); i++; chromo.add(i, ele);
pat = selectCorrPat(ele); i++; chromo.add(i, pat); i++; addOp(i); } }
private List emailPop ; private int maxpop = 50; private Random popln = new Random();
// Constructor to create a specified number of random chromosomes in the population
public EmailPopulation() { maxpop = 50; for(int i = 0; i < maxpop; i++) { ec = new EmailChromosome();//LINE 36 emailPop.add(i, ec);
}
public class FilterManager {
public static void main (String[] args) { // Creates EmailElement, EmailPattern and EmailOperator objects
EmailElement ee1 = new EmailElement(); EmailPattern ep1 = new EmailPattern(); EmailOperator eo1 = new EmailOperator();
// Creates Random, EmailPopulation, Spam Chromosome and FitnessFunction objects
Random rand = new Random(); EmailPopulation pop1 = new EmailPopulation(); //LINE 41 EmailChromosome chrm1 = new EmailChromosome(); FitnessFunction fit1 = new FitnessFunction();
}
Exception in thread "main" java.lang.NullPointerException at EmailChromosome.<init>(EmailChromosome.java:74) at EmailPopulation.<init>(EmailPopulation.java:36) at FilterManager.main(FilterManager.java:41)
Any help will be really appreciated. Thanks, Smeeta