I am trying to read names from a file into an String array and use binary search to find the name based on what the user types in but I keep getting a null pointer exception? I feel like it has something to do with the comparators when seeing if anything returns a null but i am not 100% sure if its that.
import java.util.*;
import java.io.*;
public class nameSearch{
static String names[];
int length;
public static void main(String[] args)throws IOException{
nameSearch sorter = new nameSearch();
File f = new File("names.txt");
Scanner scan = new Scanner(f);
Scanner input = new Scanner(System.in);
names = new String[65];
int counter = 0;
while(scan.hasNext()){
counter = counter + 1;
scan.next();
for(int i=0; i < counter; i=i+1){
names[i] = scan.next();
System.out.println(names[i].toString());
}
}
sorter.sort(names);
System.out.println(names.toString());
scan.close();
System.out.println("Enter a name you want to search: ");
String s = input.nextLine();
sorter.binarySearch(s, names);
}
public String toString(){
return "Name: "+ names;
}
void sort(String[] array) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
void binarySearch(String s, String[] ar){
String stringToFind = s;
int lowestIndex = 0;
int highestIndex = ar.length-1;
int middleIndex = 0;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(stringToFind.compareTo(ar[middleIndex]) > 0){
lowestIndex = middleIndex+1;
}else if(stringToFind.compareTo(ar[middleIndex]) < 0){
highestIndex = middleIndex - 1;
}else{
break;
}
}
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found at " + middleIndex);
}
}
}
The compiler is telling me that there is a null pointer exception on: sorter.sort(names) , quicksort(0, length-1), and starting at:
while (this.names[i].compareToIgnoreCase(pivot) < 0) {