我试图使用compareTo()方法对String数组进行排序,同时用户继续将字符串输入到数组中。但我不断收到错误: 线程“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)
请帮助我,谢谢
答案 0 :(得分:1)
始终检查您的输入并确保其正确并符合预期。
最有可能的肯定是问题:
titles[numDVDs-1]
是null
。因此,您正在尝试compareTo(null)
给出NPE。