我是一个新手程序员,正在学校的项目中卡了几天。目标是将一个包含单词的数组(每个位置都是不同的单词)按字母顺序排序。我已经在stackoverflow上做了一些研究,但是我有点难以理解我找到的一些示例。类和驱动程序(如果你愿意,我正在使用两部分设置)都可以编译,没有问题。问题出现在我尝试从我的驱动程序中使用
我想我应该把整个方法都包括进来,以防我的错误发生在排序部分之前。到目前为止,我找到了以下代码(我在Stack overflow上找到了它)。
非常感谢您的帮助。请在回答时尽可能详细(因为我是Java新手)。谢谢:)
编辑:为了测试空值(我假设是数组列表中的空白点),我编写了以下方法:
alphaSort
时。我在下面标记的行收到一个空指针异常。过去我也遇到过这些异常,所以我确定这是我忽略了一些小问题。但正如我所说,我还不够熟练,无法捕捉这样的小错误。我想我应该把整个方法都包括进来,以防我的错误发生在排序部分之前。到目前为止,我找到了以下代码(我在Stack overflow上找到了它)。
public void alphaSort()
{
String alphaList[] = new String[wordList.size()];
int count=0;
//puts wordList into alphaList for easier sorting
while(count<wordList.size()-1)
{
alphaList[count]=wordList.get(count);
count++;
}
int shortestStringIndex;
//sort begins here
for(int j=0; j<alphaList.length -1; j++)
{
shortestStringIndex = j;
for(int i=j+1; i<alphaList.length; i++)
{
if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
{
shortestStringIndex = i;
}
}
if(shortestStringIndex !=j)
{
String temp = alphaList[j];
alphaList[j] = alphaList[shortestStringIndex];
alphaList[shortestStringIndex]=temp;
}
}
//prints out results
count=0;
while(count<alphaList.length)
{
System.out.println(alphaList[count]);
alphaOut.print(alphaList[count]);
count++;
}
}
非常感谢您的帮助。请在回答时尽可能详细(因为我是Java新手)。谢谢:)
编辑:为了测试空值(我假设是数组列表中的空白点),我编写了以下方法:
public void isNull()
{
int count=0;
while(count<wordList.size()-1)
{
if((wordList.get(count)).equals(""))
{
System.out.println("null");
break;
}
else
{
System.out.println("nothing yet");
}
count++;
}
}
while循环从未提前退出,我的方法运行完成。
null
。一个null
引用是指一个变量根本不包含任何字符串值。例如:String a = null
。要测试isNull
,只需简单地说if (string == null)
。 - nbrooks