I've been trying to work around this NullPointerException issue:
Exception in thread "main" java.lang.NullPointerException
at LinearSearcher.<init>(LinearSearcher.java:12)
at DemoSearches.main(DemoSearches.java:4)
through researching, I found that this exception occurs when you declare a reference type but don't create an object. In my case it is when I am trying to declare LinearSearcher
I've tried to understand this with my code but i'm having difficulties
Code for LinearSearcher:
public class LinearSearcher implements Searcher {
private int[] numbers;
public LinearSearcher() {
numbers[0] = 1; // Line 12 Here
numbers[1] = 10;
numbers[2] = 20;
numbers[3] = 30;
numbers[4] = 40;
numbers[5] = 50;
numbers[6] = 60;
numbers[7] = 70;
numbers[8] = 80;
numbers[9] = 90;
}
public int searchFor(int key) {
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == key) {
return i;
}
}
return NOT_FOUND;
}
public void display() {
for (int i = 0; i < numbers.length; i++){
}
}
}
Class where LinearSearcher is declared:
public class DemoSearches {
public static void main(String args[]) {
LinearSearcher search = new LinearSearcher(); // Line 4 Here
search.display();
search.searchFor(50);
search.searchFor(100);
}
}