Search code examples
javaarraysstringsortingcompareto

Sort String using compareTo()


I was trying to use the compareTo() method to sort the String array while the user keep inputting Strings into array. But I keep getting errors of: Exception in thread "main" java.lang.NullPointerException at java.lang.String.compareTo(Unknown Source)

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int numsDVD =0; //eSize
    String [] DVD = new String [128];
    int [] Length = new int[128];
    String choice = "";
    do
    {
        if(choice.equalsIgnoreCase("a")&&numsDVD<=DVD.length-1)
        {
            numsDVD=addDVD(DVD, Length, numsDVD, input);
        }
    }while(!(choice.equalsIgnoreCase("Q")));
    input.close();
}

public static void sortedinsert(String[] titles, int[] lengths, int numDVDs, String DVD, int length)
{
    System.out.println("Index to compare : " + (numDVDs-1));
    if(DVD.compareTo(titles[numDVDs-1])>=0)
    {
        titles[numDVDs]=DVD;
    }
    else if(DVD.compareTo(titles[numDVDs-1])<0)
    {
        for(int i=0; i<numDVDs-1; ++i)
        {
            int search = numDVDs-i;
            String tmpString = "";
            int tmplength = 0;
            if(DVD.compareTo(titles[search])>0)
            {
                for(int j=numDVDs; j>numDVDs-1; --j)
                {
                    tmpString=titles[j-1];
                    tmplength=lengths[j-1];
                    titles[j]=tmpString;
                    lengths[j]=tmplength;
                }
                break;
            }
        }
        for (int i =0; i<numDVDs; ++i)
        {
            System.out.println(titles[i]);
        }
    }
}
// add to titles and lengths arrays at index numDVDs

// return numDVDs + 1
public static int addDVD(String[] titles, int[] lengths, int numDVDs, Scanner stdIn)
{
    if(numDVDs==0)
    {
        titles[numDVDs]=getvalidatedinfo(stdIn, "Please enter DVD Title : ", "");
        lengths[numDVDs]=getvalidatedinfo(stdIn, "Please enter DVD Length : ", 0);
    }
    else
    {
        String input = getvalidatedinfo(stdIn, "Please enter DVD Title : ", "");
        int length = getvalidatedinfo(stdIn, "Please enter DVD Length: ", 0);
        sortedinsert(titles, lengths, numDVDs, input, length);
    }
    return numDVDs + 1;
}

And this is the errors I keep getting

Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at Moviecheckeradv.sortedinsert(Moviecheckeradv.java:105)
at Moviecheckeradv.addDVD(Moviecheckeradv.java:148)
at Moviecheckeradv.main(Moviecheckeradv.java:21)

Please help me, Thank you


Solution

  • Always check your input and make sure it is correct and as expected. Most likely definitely the problem is that:

    titles[numDVDs-1]
    

    is null. Thus you're trying to compareTo(null) which gives the NPE.