有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java排序字符串数组提供NullPointerException

您好,我已经实现了这个基本的程序,它应该对插入的字符串进行排序,但是不知为什么它无法插入字符串。 例如,如果我实施:

TestSort t = new TestSort();
t.i("abc");
t.i("aab");

有人能看到错误并帮我修复这个错误吗

多谢各位


代码如下:

public class TestSort {
    private int length;
    String[] data;

    public TestSort() {
        length = 0;
    }

    public void i(String value) {
        data[length] = value;   
        setSorted(data);
        length++;
    }

    public void setSorted(String data[]) {
        for(int i = data.length-1; i >= 0; i--) {
            for(int j = 0; j < i; j++) {
                if(data[j].compareTo(data[j + 1]) > -1) {
                    String temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }

        for(int i = 0; i < data.length; i++) {
            System.out.print(data[i] +" ");
        }
    }
}

共 (5) 个答案

  1. # 1 楼答案

    一个有效的例子,但仍然是:使用列表,生活就容易多了:-)

    public class Test {
    private int length;
    private String[] data;
    
    public Test(int arrayLength) {
        // INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
        data = new String[arrayLength];
        length = 0;
    }
    
    public void i(String value) {
        data[length] = value;
        length++;
    }
    
    public void setSorted() {
        for (int j = 0; j < data.length - 1; j++) {
               if (data[j].compareTo(data[j + 1]) > -1) {
                    String temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
    
        }
        for (String s : data) {
            System.out.println(s);
        }
    }
    
    public static void main(String[] args) {
        Test t = new Test(5);
        t.i("bbb");
        t.i("aaa");
        t.i("ccc");
        t.i("zzz");
        t.i("ddd");
        // USE SETSORTED HERE --> else you fill your array with the same elements
        t.setSorted();
    }
    

    }

  2. # 2 楼答案

    您可以将构造函数代码更改为(字符串数组最大长度可以作为输入参数):

    public testsort() 
    

    {

       data = new String[10];
       length = 0;
    

    }

    但如果您不确定数组的大小,可以使用ArrayList

    您得到异常是因为您正在与仍然为空的数据[j+1]进行比较。 你第一次打电话的时候

    t.i("abc");
    

    数据数组中只有一个引用指向字符串文字“abc”,它位于索引0处。索引1仍然指空。 第一个字符串已经排序,所以不需要排序。如果有多个字符串,那么应该调用setSorted()方法

    要解决这个问题,您可以将您的条件放入循环中,如下所示:

    if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))
    
  3. # 3 楼答案

    不初始化数组数据。所以它被设置为null,使用数据[i]进行访问将得到一个NullPointerException。即使您初始化这个字段,它也不会工作,因为Java中的数组具有固定的大小,如果插入新值,您必须重新分配数组。您应该尝试列表实现

    所以代码应该在构造函数中初始化:

    data = new ArrayList<String>();
    

    插入将更改为

    data.add(value);
    
  4. # 4 楼答案

    变量“data”为null,因为它没有初始化,因此会出现null指针异常。由于“数据”是一个数组,根据规则,每当定义数组时,它都必须具有定义的长度。如果我们考虑你的情况。“数据”可以初始化为:-

     String[] data = new String[any numerical value]
    

    数值将是它的长度,即它能容纳的最大元素数

    其次,根据您的计划声明:

    data[length] = value;
    

    试图在数据的[length]索引上赋值,这是完全错误的,因为你还没有定义长度,所以你怎么能猜出索引的值。因此你的这种方法在逻辑上是错误的。 对于这种情况,即当我们不知道数组的长度时,建议使用ArrayList。因此,您的程序可以通过两种方式重新编写:-

    1)定义数组的长度

    String[] data = new String[n];
    

    其中n的范围至少为1到任意正整数

    2)使用ArrayList

    public class Main {
        List<String> data;
    
        public Main(){
            data = new ArrayList<String>();
        }
    
        public static void main(String... q){
    
            Main m = new Main();
            m.insertData("abc");
            m.insertData("zxy");
            m.insertData("aab");
            m.insertData("aaa");
            m.showData();
    
        }
    
        public void insertData(String str){
            data.add(str);
            Collections.sort(data);
        }
    
        public void showData(){
            if(data!=null && !data.isEmpty()){
                for(String s : data){
                    System.out.println(s);
                }
            }
        }
    
    
    }
    

    输出:-

    aaa

    aab

    abc

    zxy

    希望这有帮助

  5. # 5 楼答案

    正如Mnementh所建议的,NPE的原因是您创建了类型为String[]的字段data,但从未初始化它

    其他答案提供了代码抛出丑陋错误的所有原因;我刚刚改进了你的代码,用List<String>替换了String[],这样你就不用再担心数组的大小了。 现在使用Collections.sort()也简化了排序

    看一看

    class test1 {
        public static void main(String[] args) {
            Test sorting = new Test();
            sorting.input("abc");
            sorting.input("cba");
            sorting.input("aab");
            sorting.setSorted();
        }
    }
    
    class Test {
        private List<String> data = new ArrayList<String>();
        public void input(String value) {data.add(value);}
        public void setSorted() {
            Collections.sort(data);
            for (String current : data) {
                System.out.println(current);
            }
        }
    }
    

    如果您使用的是Java 8,那么您可以使用Arrays.parallerSort(),它执行排序的方式与Collection.sort相同,但具有并行实现

    Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the sorting operation sequentially in the calling thread. This enhancement will offer the same set of sorting operations currently provided by the Arrays class, but with a parallel implementation that utilizes the Fork/Join framework. These new API's are still synchronous with regard to the calling thread as it will not proceed past the sorting operation until the parallel sort is complete.

    要实现它,请在上述代码中将Collections.sort替换为Arrays.parallelSort

    取代

    Collections.sort(data);
    

    带着

    Arrays.parallelSort(data.toArray(new String[data.size()]));