The reason i ask this question is because i still get a null pointer exception even tho i am sure there is no issue but as usual there probably is some massive mistake i have made :D
The lecture slides said this
1) Use variables to store the start-index and length of the sequence of array elements that must contain Mike's entry if there is one.
2) Set start-index to 0 and length to the array length.
3) while length is greater than 1
a) Compare Mike with the name in the middle element (at start_index + length/2)
b) If it is earlier then set length to length/2 and leave start-index as it is.
c) If it is later or equal then add length/2 to start-index and subtract length/2 from length
4) length is now 1 so it must be Mike's entry if he has one.
here is my code (its the search method in the record in phonebook i am changing). Just to add, the programme loads a text file that stores names and numbers in the following formats, on seperate lines
258132 Adams, Aaron
199644 Adams, Abacuck
567480 Adams, Abraham
810323 Adams, Adam
444601 Adams, Adlard
/**
* Write a description of class Record here.
*
* @author John Bovey
* @version 29 September 2009
*/
public class Record
{
private String name;
private String number;
public Record(String name, String number)
{
this.name = name;
this.number = number;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
}
import java.io.*;
/**
* @author John Bovey
* @version 29 September 2009
*/
public class PhoneBook
{
static final int MAX_RECORDS = 50000;
private Record list[];
private int length;
/**
* Constructor for objects of class PhoneBook
*/
public PhoneBook(String file) throws FileNotFoundException
{
list = new Record[MAX_RECORDS];
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String s = br.readLine();
length = 0;
while (s != null) {
String[] args = s.split(" ", 2);
list[length] = new Record(args[1], args[0]);
s = br.readLine();
length++;
}
}
catch (IOException e) {
}
}
**/**
* Look a name and return the number or null if there is no match
*/
public String search (String name)
{
int startIndex = 0;
int length = list.length;
while(length > 1){
if(name.compareToIgnoreCase(list[startIndex + (length / 2)].getName()) > 0) {
length = length / 2;
}
else{
startIndex = startIndex + (length / 2);
length = length - (length / 2);
}
}
return list[startIndex + (length / 2)].getNumber();
}**
/**
* Test the search method by looking up each name in turn
*/
public void testSearch()
{
for (int i = 0; i < length; i++) {
String name = list[i].getName();
String num_correct = list[i].getNumber();
String num_search = search(name);
if (!(num_correct.equals(num_search))) {
System.out.printf("Failed for %s - search returned %s instead of %s\n", name, num_search, num_correct);
return;
}
}
System.out.println("Ok.");
}
}