-2

So, I was given the task of writing two simple methods for an array: the first method, double the size of the array; the second method, find the index of the first duplicate string in the array. The main method was written by my professor and is not to be altered. My problem is that I continue to get a NullPointerException when running my code. I believe it has to do with Arrays.sort() or my teacher's code in main, but I was instructed to: only use arrays (no other data structure), use Arrays.sort() in finding the index of the dupe, and not to modify anything else in the program...is there any way I can rewrite my methods keeping to these instructions?

Full code:

import java.io.*;
import java.util.*;

public class Practice
{
    static final int CAPACITY = 10;
    static final int NOT_FOUND = -1;
    public static void main (String[] args) throws Exception
    {
        if (args.length < 1 )
        {
            System.out.println("\nusage: C:\\> java Practice <words filename>\n\n"); // i.e. C:\> java Lab2 10Kints.txt 172822words.txt
            System.exit(0);
        }


    String[] wordList = new String[CAPACITY];
    int wordCount = 0;
    BufferedReader wordFile = new BufferedReader( new FileReader(args[0]) );

    while ( wordFile.ready() ) // i.e. while there is another line (word) in the file
    {   if ( wordCount == wordList.length ) 
            wordList = upSizeArr( wordList );
        wordList[wordCount++] = wordFile.readLine();
    } //END WHILE wordFile
    wordFile.close(); 
    System.out.format( "%s loaded into word array. size=%d, count=%d\n",args[0],wordList.length,wordCount );
    int dupeIndex = indexOfFirstDupe( wordList, wordCount );
    if ( dupeIndex == NOT_FOUND )
        System.out.format("No duplicate values found in wordList\n");
    else
        System.out.format("First duplicate value in wordList found at index %d\n",dupeIndex);

} // END OF MAIN

// TWO METHODS 

static String[] upSizeArr( String[] fullArr )
{

    int size = fullArr.length; //find the length of the arrays
    String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
    for (int a = 0; a < size; a++) {
        newSizeArr[a] = fullArr[a];
    }
    return newSizeArr;

}
static int indexOfFirstDupe( String[] arr, int count )
{       
    Arrays.sort(arr);
    int size = arr.length;
    int index = NOT_FOUND;

    for (int x = 0; x < size; x++) {
        for (int y = x + 1; y < size; y++) {
            if (arr[x].equals(arr[y])) {
                index = x;
                break;
            }
        }
    }
    return index;
}
} // END OF PROGRAM

Location of the NullPointerException:

enter image description here

Edit: This question addresses an NPE in library code, not my own code.

noob4lyfe
  • 53
  • 4
  • From the error output, you can see that the NPE is coming from your indexOfFirstDupe method. And there is only one line in that method that could cause that exception - the line where you index the array. The nested for starts from x + 1, but x will increment all the way up to the end of the array. When that happens, y = size, but arr[size] doesn't exist because the indices go from 0 to size - 1. – bitscuit Oct 07 '18 at 04:41
  • The problem is very easy to understand. you create an array of size 10 at first, but if argument send to your program less than 10, then the array contain `null` in it so `Arrays.sort()` can't do job. it happens when you double you size array too. these happens because default of `String` is `null`. – Amin Oct 07 '18 at 04:42
  • I beg to differ on the duplicate call. The linked original is about NPE in one’s own code. This question is about an undocumented NPE deep inside library code. – Ole V.V. Oct 07 '18 at 05:02
  • The problem is that I have to use Arrays.sort() per professor's request. Anyway to get around that? – noob4lyfe Oct 07 '18 at 05:33
  • As far as I can see, your stacktrace is from the command prompt in Windows? It is possible to mark (select) text in the command prompt and copy it from there. So it’s better to do that and paste it into the question, then format as code to preserve the way it’s formatted. Images have their place, but images of text are not popular here. – Ole V.V. Oct 07 '18 at 06:02
  • @noob4lyfe Maybe you will want to accept the answer by clicking the tick mark to the left of it? Please see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Ole V.V. Oct 14 '18 at 04:57

1 Answers1

0

According to the image of the stacktrace the NPE happens inside Arrays.sort(). While not documented (that I can see), I believe that this method throws the NPE if the array contains a null. What else could it reasonably do? A null cannot have a natural place in the natural order, so an array containing a null cannot be sorted with Arrays.sort(Object[]).

How to fix? I don’t see the meaning of sorting the array, so you may just leave it out. Sorting means that the returned index of the first duplicate is not a valid index into the original array (from before sorting). However, if your professor insists, you can fix through appropriate use of the overloaded Arrays.sort(Object[] a, int fromIndex, int toIndex) so you only sort the part of the array where the strings are.

I was instructed to … use Arrays.sort() in finding the index of the dupe

Edit: If you just need to find any duplicate, Arrays.sort() can help. After sorting you know that any duplicates end up together in the array, right beside each other. So now you only need to compare each element to the next element, not to every other element of the array, to determine whether there is a duplicate and find one if there is. However, generally the first duplicate in the sorted array will not be the same as the first duplicate in the unsorted array.

For example: Unsorted array:

    ["pig", "cow", "queen", "cow", "bee", "bee"]

First duplicate: cow. First index of cow: 1.

After sorting:

    ["bee", "bee", "cow", "cow", "pig", "queen"]

First duplicate: bee. First index of bee: 0.

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
  • Ah, that might work. But how do I know which index to start and stop from since I doubled the array's size? The array size is "327680" and the strings in the array is "172822"... – noob4lyfe Oct 07 '18 at 06:00
  • Think. You can do this. Do you know how many strings are in the array? 172822? Do you know where in the array they are? From which index to which index? – Ole V.V. Oct 07 '18 at 06:04
  • Ole V. V. -- you da man (or woman)! You just solved a problem I've had for about two weeks now! Thank you thank you thank you...I was seconds away from throwing my PC out the window xD Thank to you, kind internet stranger, I can sleep easy now :) ! – noob4lyfe Oct 07 '18 at 06:23