[英]Not sure why I'm getting a NullPointerException error
因此,我正在運行一個對String數組執行各種操作的程序。 其中之一是在數組內插入字符串並對其進行排序。 我可以使用sort方法,但是當我嘗試插入一個字符串然后對其進行排序時,我得到了NullPointerException。 這是代碼:
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
我該如何解決?
您有5個字符串的數組,但是只有3個被初始化。 其余的都指向null(因為您沒有初始化它們):
String [] words = new String[5];
words[0] = "telephone";
words[1] = "shark";
words[2] = "bob";
words[3] = null;
words[4] = null;
第一行僅初始化數組本身,而不初始化包含的對象。
但是插入會迭代所有5個元素。 當我為3時,temp為null。因此,語句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)
解決方案:同時在while循環中檢查temp是否為null。 或者根本不使用字符串數組,而是使用可自動調整大小的數據結構列表java.util.ArrayList。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.