I have been doing this homework assignment for some time now and cannot figure out how to fix this null pointer error I am getting. I think it is an issue with int[] a in my code and it not being initialized before i call on a.length:
class target{
int arraySearch(int a[], int target){
for(int index = 0; index < a.length; index++){
if(a[index] == target)
return index;
}
return -1;
}
public void main(String[] args) {
target t = new target();
int test1[] = {15,20,5,11};
int test2[] = {15,20,7,11};
System.out.println("Testing arraySearch with target = 5 and array of 15,20,5,11: " + t.arraySearch(test1,5));
System.out.println("Testing arraySearch with target = 5 and array of 15,20,7,11: " + t.arraySearch(test2,5));
}
}
If you guys could please help me and explain what is wrong that would be greatly appreciated. I am having this error on other parts of my homework and would like to fix them myself. All advice is appreciated.
Target
– Drew Galbraith Apr 4 '14 at 6:30main
should be defined asstatic
. Other than that, the given code snippet runs fine as does not produce aNullPointerException
. – Mureinik Apr 4 '14 at 6:32