首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不确定为什么会收到NullPointerException错误

不确定为什么会收到NullPointerException错误
EN

Stack Overflow用户
提问于 2014-04-10 05:05:31
回答 1查看 90关注 0票数 0

所以我正在运行一个对字符串数组执行各种操作的程序。其中之一是在数组中插入一个字符串并对其进行排序。我可以使用sort方法,但是当我尝试插入一个字符串,然后对它进行排序时,我得到了一个NullPointerException。代码如下:

代码语言:javascript
复制
    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文件本身:

代码语言:javascript
复制
    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

我该怎么解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2014-04-10 05:11:37

您有一个由5个字符串组成的数组,但其中只有3个字符串已初始化。rest指向null (因为您没有初始化它们):

代码语言:javascript
复制
  String [] words = new String[5];
  words[0] = "telephone";
  words[1] = "shark";
  words[2] = "bob";
  words[3] = null;
  words[4] = null;

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

但是插入遍历了所有5个元素。当i为3时,temp为null,所以语句temp.compareTo抛出一个NullPointerException。

代码语言:javascript
复制
 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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22973918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档