Java 不知道为什么我';我收到一个NullPointerException错误
所以我正在运行一个程序,对字符串数组执行各种操作。其中之一是在数组中插入字符串并对其排序。我可以使用sort方法,但是当我尝试插入一个字符串并对其进行排序时,会得到一个NullPointerException。代码如下:Java 不知道为什么我';我收到一个NullPointerException错误,java,nullpointerexception,Java,Nullpointerexception,所以我正在运行一个程序,对字符串数组执行各种操作。其中之一是在数组中插入字符串并对其排序。我可以使用sort方法,但是当我尝试插入一个字符串并对其进行排序时,会得到一个NullPointerException。代码如下: import java.util.Scanner; import java.io.*; public class List_Driver { public static void main(String args[])
import java.util.Scanner;
import java.io.*;
public class List_Driver
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
int choice = 1;
int checker = 0;
String [] words = new String[5];
words[0] = "telephone";
words[1] = "shark";
words[2] = "bob";
ListWB first = new ListWB(words);
int menu = uWB.getI("1. Linear Seach\n2. Binary Search\n3. Insertion in Order\n4. Swap\n5. Change\n6. Add\n7. Delete\n8. Insertion Sort\n9. Quit\n");
switch(menu)
{
//other cases
case 3:
{
String insert = uWB.getS("What term are you inserting?");
first.insertionInOrder(insert);
first.display();
}//not working
break;
}//switch menu
}//main
}//List_Driver
uWB是一种基本的util驱动程序。它没有任何问题。这是ListWB文件本身:
public class ListWB
{
public void insertionSort()
{
for(int i = 1; i < size; i++)
{
String temp = list[i];
int j = i;
while(j > 0 && temp.compareTo(list[j-1])<0)
{
list[j] = list[j-1];
j = j-1;
}
list[j] = temp;
}
}
public void insertionInOrder(String str)
{
insertionSort();
int index = 0;
if(size + 1 <= list.length)
{
while(index < size && str.compareTo(list[index])>0)
index++;
size++;
for (int x = size -1; x> index; x--)
list[x] = list[x-1];
list[index] = str;
}
else
System.out.println("Capacity Reached");
}//insertioninorder
}//ListWB
公共类列表wb
{
public void insertionSort()
{
对于(int i=1;i0&&temp.compareTo(列表[j-1])索引;x--)
列表[x]=列表[x-1];
列表[索引]=str;
}
其他的
系统输出打印项次(“达到容量”);
}//插入诺德
}//列表WB
如何修复此问题?您有一个包含5个字符串的数组,但其中只有3个已初始化。其余部分指向null(因为您没有初始化它们): 第一行仅初始化数组本身,但不初始化包含的对象 但是insert会迭代所有5个元素。当我3岁时,temp为空。因此,语句temp.compareTo抛出一个NullPointerException
for(int i = 1; i < size; i++)
{
String temp = list[i];
int j = i;
while(j > 0 && temp.compareTo(list[j-1])<0)
for(int i=1;i 而(j>0和温度比较(列表[j-1])请发布异常StackTrace可能的副本,您似乎忽略了堆栈跟踪,它准确地告诉您错误发生的位置,然后结合a的定义,可以直接确定什么是null
。然后查看代码并确定为什么null
,以及不要这样做,或者处理它。不要忽略堆栈跟踪。
for(int i = 1; i < size; i++)
{
String temp = list[i];
int j = i;
while(j > 0 && temp.compareTo(list[j-1])<0)