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:
publicclass 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;
publicint nextIndex = 0;
publicdouble[] confiVals1 = newdouble[3];
publicdouble[] confiVals2 = newdouble[3];
publicdouble[] confiVals3 = newdouble[3];
private List child1;
private List child2;
privateint 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 using the "selectCorrPat"
// method
pat = selectCorrPat(ele);
chromo.add(i, pat);
i++;
// The "addOp" method randomnly adds an operator to the list
addOp(i);
i++;
ele.setToFd('t');
chromo.add(i, ele);
// The pattern after the "To" element will essentially be my name.
pat.setRecvrName("smeeta");
i++;
chromo.add(i, pat);
i++;
addOp(i);
ele.setCcFd('c');
i++;
chromo.add(i, ele);
// 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);
}
}
publicclass EmailPopulation
{
// Private instance variables
private EmailChromosome ec;
private List emailPop ;
privateint 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);
}
publicclass FilterManager
{
publicstaticvoid 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();
}
The error message is as follows:
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)
If I change my data structure from List to Vector and intialise the vector to: Vector chromo = new Vector(18); I no longer get this exception. However I cannot do this with a List as a List has no consructor where the size is to be specified as in a vector.
Any help to tackle this problem will be really appreciated. Thanks, Smeeta
The problem is an unitialized variable in line 74 of EmailChromosome.java
I can not tell which line that is from your post. One of the variables called in that line was declared but not initialized before it was being calle din line 74. Because it is null, execution is giving you a null pointer exception
I can not compile your code because you have not included all the class files including: EmailElement EmailPattern EmailOperator
The class Vector implements the List interface. So you can create a List object with a line of code such as:
List chromo = new Vector(18);
the 18 is just the initial capacity which is optional. So you could use:
Hi Charles, Thankyou for your reply. I just initialised the List to List chromo = new Vector(); and then I didnt get the Null Pointer Exception! However I got the null pointer exception in another part of my code, soon after this. Please can you help me with this one? I have included all my test class below:
import java.util.List;
import java.util.Vector;
import java.util.Hashtable;
import java.lang.Double;
import java.util.StringTokenizer;
import java.util.*;
publicclass Trial
{
public Hashtable spamPatLUT = new Hashtable(2);
publicdouble[] spamProbabilities = newdouble[2];
publicvoid createPat(String sPat, double sProb)
{
int nextIndex = 0;
// double[] spamProbabilities = new double[2];
Integer nextInd = new Integer(nextIndex);
spamPatLUT.put(nextInd, new String(sPat));
spamProbabilities[nextIndex] = sProb;
nextIndex += 1;
}
public Hashtable getSpamPatLUT()
{
return spamPatLUT;
}
public String getSpamNamesLUT(int i)throws NameNotFoundException
{
String s;
// If name is not found, the hashtable will throw an exception.
try{
Integer index = new Integer(i);
s = (String)spamPatLUT.get(index);
}
catch(Exception e) {
// We catch the hashtable exception and throw our own.
thrownew NameNotFoundException("Specified name not present");
}
String ss = s.toString();// LINE 42
return ss;
}
publicdouble getSpamProbabilities(int index)
{
return spamProbabilities[index];
}
}
import java.util.List;
import java.util.Vector;
import java.util.Hashtable;
import java.lang.Double;
import java.util.StringTokenizer;
publicclass TrialPrint
{
// Print contents of string tokenizer
publicstaticvoid main (String[] args)
{
Trial t = new Trial();
Hashtable spamPatLUT = new Hashtable(2);
double[] spamProbabilities = newdouble[2];
String spamName;
double prob = 0.0;
FileInput sNames = new FileInput("SpamNames.txt") ;
String spamNamesFile = sNames.readString();
while (!sNames.eof())
{
StringTokenizer st1 = new StringTokenizer(spamNamesFile, ":");
while (st1.hasMoreTokens())
{
// Inserting the spam names into the Hashtable and the scores into the array
spamName = st1.nextToken();
prob = Double.parseDouble(st1.nextToken());
t.createPat(spamName , prob);
System.out.println(t.getSpamNamesLUT(1));
}
spamNamesFile = sNames.readString();
}// LINE 36
sNames.close();
}
}
The file being read in and string tokenized is: "SpamNames.txt" is as follows:
"123":0.88 "bananalotto":0.91
The error message is as follows:-
Exception in thread "main" java.lang.NullPointerException at Trial.getSpamNamesLUT(Trial.java:42) at TrialPrint.main(TrialPrint.java:36)
I have marked lines 42 and 36 in the appropriate classes above. (I am not too sure about whether I need to throw the extra exception, NameNotFoundException- with or without throwing this I still get the Null Pointer Exception.)
Though I have not compiled your code, you may be getting an exception due to the logic in createPat method. You are saving a string with key as "0". 'nextIndex' is initialized to 0 every time createPat is called as it is declared inside the method. While retrieving 't.getSpamNamesLUT(1))', you are using index=1, which is not there in the Hashtable. Hence the NullPointerException.
Hi Arun, thanks for replying. I put, int nextIndex = 0, outside the createPat method. I also changed my method call to t.getSpamNamesLUT(0) but it still gave the same exception.