-1

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);

 }
}
Gurbs
  • 1

3 Answers3

4

numbers is null because you haven't initialized it. You can change

private int[] numbers;

to

private int[] numbers = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

and eliminate the problem. Other solution, add

numbers = new int[10];

Before your current assignments.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

You never initialize the numbers array so when you try to access it in the LinearSearcher constructor you are trying to access a nonexistent array. So an exception is thrown.

Tomer Aberbach
  • 536
  • 3
  • 11
0

You need to do numbers = new int[10]; before doing numbers[0] etc. This will create the object so it can be used.

Charanor
  • 810
  • 8
  • 23