使用 compareTo() 对字符串进行排序

Sort String using compareTo()

我正在尝试使用 compareTo() 方法对字符串数组进行排序,同时用户不断将字符串输入数组。但我不断收到以下错误: 线程异常 "main" java.lang.NullPointerException 在 java.lang.String.compareTo(来源不明)

    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;
}

这是我不断收到的错误

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)

请帮帮我,谢谢

始终检查您的输入并确保其正确且符合预期。 很有可能肯定是问题所在:

titles[numDVDs-1]

null。因此,您正在尝试 compareTo(null) 这给出了 NPE。