2014-04-09 42 views
0

所以我正在运行一个程序,对String数组执行各种操作。其中之一是在数组中插入一个字符串并对其进行排序。我能够使用排序方法,但是当我尝试插入一个字符串然后对其进行排序时,我得到一个NullPointerException。这是代码:不知道为什么我得到一个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 

我该如何解决这个问题?

+3

请发布异常堆栈跟踪 –

+0

可能的重复[什么是空指针异常?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception) –

+1

您似乎已经忽略了你的堆栈跟踪,它会精确地告诉你错误发生的位置,然后结合['NullPointerException']的定义(http://docs.oracle.com/javase/7/docs/api/java/lang/ NullPointerException.html),确定什么是null是很简单的。然后你看看你的代码,并确定*为什么*它是'null',并且不是这样,或者处理它。不要忽视堆栈跟踪。 –

回答

1

你有一个5个字符串的数组,但只有3个初始化。其余的点为空(因为你没有初始化它们):

String [] words = new String[5]; 
    words[0] = "telephone"; 
    words[1] = "shark"; 
    words[2] = "bob"; 
    words[3] = null; 
    words[4] = null; 

第一行只初始化数组本身,而不是其所包含的对象。

但插入迭代所有5个元素。 temp是null,当我是3.所以语句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为空。或者根本不使用字符串数组,而是使用可自动调整大小的数据结构列表java.util.ArrayList。

相关问题