NullPointerException error when running the program, I cant figure out why. the exact error is Exception in thread “main” java.lang.NullPointerException
at EditDistance.editDistance(EditDistance.java:32)
at EditDistance.main(EditDistance.java:19)
import java.util.ArrayList;
public class EditDistance
{
public static void main(String[] args)
{
ArrayList<Character> a = new ArrayList<Character>();
char[] xArray = null;
char[]yArray = null;
char[] finalY = null;
String x = "AACAGTTACC";
String y = "TAAGGTCA--";
xArray = x.toCharArray();
yArray = y.toCharArray();
a = toArrayList(a , yArray);
System.out.println(editDistance(a, xArray, finalY, y));
}
public static int editDistance(ArrayList<Character> a, char[] xArray, char[] finalY, String y)
{
int temp;
for(int i = 0; i<xArray.length; i++)
{
temp = y.indexOf(xArray[i]);
if(temp != -1)
{
finalY[i] = a.get(temp);
a.remove(temp);
y = (y.substring(0, temp) + y.substring(temp));
}
else if(y.indexOf(xArray[i])==-1)
{
xArray[i]='z';
}
}
for(int j =0; j<xArray.length; j++)
{
if(xArray[j]=='z')
{
finalY[j]=a.get(j);
}
}
int result = calcScore(finalY, xArray);
return result;
}
public static ArrayList<Character> toArrayList(ArrayList<Character> a, char[] yArray)
{
for(int i=0; i<yArray.length;i++)
{
a.add(yArray[i]);
}
return a;
}
public static int calcScore(char[] finalY, char[] xArray )
{
int number = 0;
for(int i=0; i <xArray.length; i++ )
{
if( finalY[i]==(xArray[i]) )
{
}
else if(finalY[i] == '-')
{
number++;
number++;
}
else if (finalY[i] != xArray[i])
{
number++;
}
}
return number;
}
}
any help is appreciated
You set
finalYto null, pass it toeditDistance, then attempt to set one of its entries.If you want to modify it in
editDistance, it must not be null.If
finalYis not used outside ofeditDistance, it should not be a parameter: declare and allocate it inside the method.