-1

I am writing a program that takes a file and writes it's contents to an array. Then the array is sorted with a selection sort algorithm and then can be searched using the binary search algorithm. The array can not have more than 100 elements and I can't use user-defined classes.

/*Griffen Fox
  CS 110
  Assignment 5
  Question 1
*/
import java.util.Scanner;
import java.io.*;
public class WordsSearchProgram
{
   public static void main(String[] args)throws IOException
   {
      //Loads Words.txt to an array
      final int SIZE = 100; //Size of the array
      String[] words = new String[SIZE]; // creates the array
      int index = 0; // Loop Control Variable

      //Opens the File
      File file = new File("words.txt");
      Scanner inputFile = new Scanner(file);

      //Reads Contents Into Array
      while (inputFile.hasNext() && index < words.length)
      {
         words[index] = inputFile.nextLine();
         index++;
      }

      //Close File
      inputFile.close();
      int search;
      for (index = 0; index < words.length; index++)  
      {  
         search = searchString(words, words[index]);  

         if (search >= 0) 
         {  
            System.out.println(words[index] + " is at index " + search);  
         }  
         else 
         {  
            System.out.println(words[index] + " is not in the array.");  
         }  
       }  
    }
    //Selection Sort Algorithm
    public static String[] sort(String[] words)
    {
      for (int i = words.length - 1; i >= 1; i--)
      {
       // Find the maximum in the list[0..i]
       String  currentMax = words[0];
       int currentMaxIndex = 0;

         for (int j = 1; j <= i; j++)
         {
            if (currentMax.compareTo(words[j]) < 0) 
            {
               currentMax = words[j];
               currentMaxIndex = j;
            }
         }

       // Swap list[i] with list[currentMaxIndex] if necessary;
       if (currentMaxIndex != i) 
       {
         words[currentMaxIndex] = words[i];
         words[i] = currentMax;
       }

      }
      return words;
      }
      //Binary Search String
      public static int searchString(String[] words, String key) 
      {  
         int first = 0;  
         int last  = words.length;
         int position = -1;
         boolean found = false;  

         while (!found && first <= last)
         {  
            int mid = ((first + last) / 2);  
            if (key.compareTo(words[mid]) == 0) 
            {  
               found = true;
               position = mid;  
            }
            else if (key.compareTo(words[mid]) > 0) 
            {  
               first = mid - 1;  
            } 
            else 
            {  
               first = mid + 1;  
            }   
          }  
         return position;  
      }
} 
user3006947
  • 29
  • 1
  • 4
  • show us where you are getting the null pointer exception? Which line? – anirudh Mar 12 '14 at 03:34
  • 1
    You can fix it once you understand **what** and **why** [NullPointerException](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html) occur – Baby Mar 12 '14 at 03:35
  • Indexes in java are started with 0 and last index is `length-1` – Iłya Bursov Mar 12 '14 at 03:35
  • 1
    Look at your stacktrace and at least figure out which line it happens – saladinxu Mar 12 '14 at 03:37
  • int last = words.length; You are using this, which gives you the length of the file and not the number of words ... here last = 100.... you need to use another array to hold the words present in the file and not store null values – Sambhav Mar 12 '14 at 03:38
  • Yeah that's why I thought the error was occurring but then how do I make sure that the array can only be 100 words? – user3006947 Mar 12 '14 at 03:46

4 Answers4

0

The size of array "words" is 100. But you fill the array with the words read from "words.txt".

What if the lines of the file is less then 100?

Then some elements of "words" will be NULL.

Jaemok Lee
  • 167
  • 4
0

Your file has less than 100 lines so the words[mid] is null!

 if (key.compareTo(words[mid]) == 0) // causes to NullPointErexception

Even if you fix this, the above line raises java.lang.ArrayIndexOutOfBoundsException so you should changes many things!

To fix the problem you could do this :

  ArrayList<String> words = new ArrayList<String>();
  ...
  words.add(inputFile.nextLine());

and change the loop condition from

while (inputFile.hasNext() && index < words.length)

to

while (inputFile.hasNext() && index < SIZE)

and simply get the size of words using words.size().

Edit : You can easily pass the words to the sort method just instead of word[index] use words.get(index) and words.set(index, element).

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
0

in your first while loop you need something like

while (inputFile.hasNext() && index < words.length)
  {
     words[index] = inputFile.nextLine();
     index++;
     numOfWords = index + 1;
  }

use the numOfWords variable as your comparison in your loops below so you never get to a point in the array where it is NULL

mig
  • 142
  • 7
0

Exactly as Mok mentioned, you need to use ArrayList instead of arrays. Moreover, one must use the predefined methods like the equals method while writing the code to avoid reinventing the wheel and also to keep the code bug free.

Use equals method

key.equals(words[mid])

or

check for null values before you use the compareTo operator.

if(key!=null && words[mid]!=null && key.compareTo(words[mid]) > 0)

using arraylist will help you solve the arrayindexoutofbounds exception

newuser
  • 8,338
  • 2
  • 25
  • 33
Aniruddha
  • 308
  • 2
  • 11