0

The error comes at null pointer when I search for an element. It successfully accepts the inputs and displays the array but when I input the search element and press enter it displays error.

It shows null pointer exception with the following stack trace.

The error when is as follows when searching the element.

Exception in thread "main" java.lang.NullPointerException
at BinarySearchClass.binarySearch(BinarySearchClass.java:26)
at BinarySearchIterative.main(BinarySearchIterative.java:25)

i.e; It says in this line

BinarySearchClass.java:26

while ((array[indexToLook] != search) && (maxIndex > minIndex)) {

and this line in the other file

BinarySearchIterative.java:25

int found = BSI.binarySearch(search);

Please help me correct it.

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearchClass {

    private  Integer[] array;

    public  BinarySearchClass(int size){
        this.array = new Integer[size];
    }

    public BinarySearchClass(){
        this(100); //default size of array.
    }

    public  int binarySearch(int search){

        int maxIndex = size()-1;
        int minIndex = 0;

        int indexToLook = (int) Math.floor((minIndex + maxIndex)/2);
        while ((array[indexToLook] != search) && (maxIndex > minIndex)) {
            if(array[indexToLook] > search) {
                maxIndex = indexToLook - 1;
            }
            else{
                minIndex = indexToLook + 1; 
            }
            indexToLook = (int) Math.floor((minIndex+maxIndex/2));
        }
        if(array[indexToLook] == search)
            return indexToLook;

        return -1;
    }

    public  int binarySearch( int search, int minIndex, int maxIndex){
        if (minIndex == maxIndex){
            if(array[minIndex] == search) 
                return minIndex;
            return -1;
        }
        int indexToLook = (int) Math.floor((minIndex + maxIndex)/2);
        if(array[indexToLook] == search){
            return indexToLook;
        }
        if(array[indexToLook] < search)
            return binarySearch( search, indexToLook+1, maxIndex );
        return binarySearch( search, minIndex, indexToLook-1);
    }

    public String toString() {
        return Arrays.deepToString(this.array);
    }

    private  int size() {
        int i = 0;
        while (((array[i] != null) && i < array.length) ) {
            i++;
        }
        return i;
    }
}

class BinarySearchIterative:

import java.util.Scanner;

public class BinarySearchIterative   {

    public static void main(String[] args){
        BinarySearchClass BSI = new BinarySearchClass(10);
        Scanner scan = new Scanner(System.in);
        System.out.println("Iterative");

        System.out.println("Enter the number of elements: ");
        int size = scan.nextInt();
        int[] array = new int[size];
        int i;
        for(i =0; i<=size-1; i++){
            System.out.println("Enter the element " + i + " :");
            array[i] = scan.nextInt();
        }
        System.out.println("The elements are");
        for(i=0; i<=size-1; i++){
            System.out.print("[" + array[i] + "]");
        }
        int search = 0;
        System.out.println("\nEnter the element to search");
        search = scan.nextInt();
        int found = BSI.binarySearch(search);
        if (found > -1)
        {
            System.out.println("The element " + search +  " is found in location " + (found+1) );
        }
        else
        {
            System.out.println("Element " + search + " not found");
        }
    }
}

EDIT (@Paul): Since the array you want to perform a binary search on is already given in BinarySearchIterative, I'd recommend this approach instead of yours:

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearchClass {
    public static int binarySearch(int search , int[] array){

        int maxIndex = size()-1;
        int minIndex = 0;

        int indexToLook = (int) Math.floor((minIndex + maxIndex)/2);
        while ((array[indexToLook] != search) && (maxIndex > minIndex)) {
            if(array[indexToLook] > search) {
                maxIndex = indexToLook - 1;
            }
            else{
                minIndex = indexToLook + 1; 
            }
            indexToLook = (int) Math.floor((minIndex+maxIndex/2));
        }
        if(array[indexToLook] == search)
            return indexToLook;

        return -1;
    }

    public static int binarySearch( int search, int minIndex, int maxIndex , int[] arr){
        if (minIndex == maxIndex){
            if(array[minIndex] == search) 
                return minIndex;
            return -1;
        }
        int indexToLook = (int) Math.floor((minIndex + maxIndex)/2);
        if(array[indexToLook] == search){
            return indexToLook;
        }
        if(array[indexToLook] < search)
            return binarySearch( search, indexToLook+1, maxIndex );
        return binarySearch( search, minIndex, indexToLook-1);
    }
}

class BinarySearchIterative:

import java.util.Scanner;

public class BinarySearchIterative   {

    public static void main(String[] args){
        ...
        int found = BinarySearchClass.binarySearch(search ,  array);
        ...
    }
}

Note that the input-array must be sorted in order to perform a binary search, which isn't ensured by your code. And there's a more general design-problem with your code. BinarySearchClass shouldn't store any arrays itself and only provide the utility-methods to search an array (with static methods, like in my example). This would be the general approach of programming: modularization. Each Class should only provide functionality for one specific purpose or should only hold data that represents a single data-set and provide functionality to handle this data. Have a look a general coding-style guide (there are tons of books, webmaterial, etc. on this topic).

Ansar
  • 1
  • 1
    pretty common mistake: you use an `Integer[]` (note that `Integer` is an Object!!!) and never intialize it with values, thus all values are `null` and comparing these values will result in a `NullPointerException`. Initialize the array properly and things should work just fine. –  Jan 22 '16 at 01:44
  • since I am new to programming ... can you tell me how to initialize them properly? – Ansar Jan 22 '16 at 01:53
  • you mean i should change the integer[] as int[] ?...... I have used Integer, rather than int, so that we can do null checks to see if data is present at a particular index or not. it will be hard to see if a 0 was really inserted as part of data, or it is the initialized 0 as java automatically initializes int... – Ansar Jan 22 '16 at 01:57
  • just assign some value to the single values Since you want to use the array for binary-search, you should use sorted values. Either directly get the array as a constructor-parameter, or generate them in the constructor. Just make sure that the array holds a value for each index. As for the change from `int[]` to `Integer[]` that would just be a workaround to solve the problem with the `Exception`. If you want to search the range, you'll have to initialize it properly anyways. –  Jan 22 '16 at 01:58
  • Thanks!... but I still couldn't figure out this way so I went on and implemented method() and It worked. But I still would like to do it this way and as I couldn't get it, will you please just edit those lines which will make this one work? would help me in learning... Thanks in advance – Ansar Jan 22 '16 at 02:32
  • its a bit late now, I'll do that tomorrow (in about 8 hrs from now) –  Jan 22 '16 at 02:42
  • awesome.... Thanks.... means a lot!... – Ansar Jan 22 '16 at 02:43
  • yeah I just saw.. and it makes sense.. thank you. – Ansar Jan 22 '16 at 15:18

0 Answers0