试图合并类的排序数组时,得到空指针异常。

我有一个成型的类叫General,里面有ID、姓名、年龄的变量。两个ints和一个字符串。然后我有一个GeneralRosters类,打开一个可序列化的文件,读取记录,对记录进行排序,然后关闭文件。我使用一个单独的MergeSort类来对记录进行排序。每当我运行我的测试程序时,我的MergeSort类一直收到一个空指针异常。我知道记录被正确地读入了我的数组,因为我可以在读入后输出整个列表。有什么想法是出了问题吗?我把我的代码贴在下面。error message

import java.io.Serializable;
public class General implements Serializable {
    private int ID;
    private String name;
    private int age;
    private static final long serialVersionUID =  6894788911163027404L;   //not an instnace variable,needed for serial file

    public General() {
        setID(0);
        setName("");
        setAge(0);
    }
    public General(int ID, String name, int age) {
        setID(ID);
        setName(name);
        setAge(age);
    }
    public int getID() {
        return ID;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public void setID(int ID) {
        this.ID = ID;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String toString() {
        return ("ID: " + ID + "\n Name: \t" + name + "\n Age: \t" + age);
    }
}
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Scanner;
public class GeneralRosters
{
    private ObjectInputStream input;
    private General [] roster = new General[20];
    // **** SORT ROUTINE *******
    public void sortRoster(){
        System.out.println("** In sortRoster **");
        MergeSort mergeSort = new MergeSort();
        mergeSort.sort(roster, 0, roster.length-1);

    }
    //  ******* OPEN FILE ROUTINE *******
    public void openFile(){
        System.out.println("** In openFile **");
        try {
            input = new ObjectInputStream(new FileInputStream("generalMaster.ser"));
        }
        catch(IOException ioException) {
            System.err.println("can't open or accesss file  " + ioException + "\n");
        }
    } 

 //******* READ FILE and LOAD ARRAY ROUTINE *******
    public void readRecords(){
        System.out.println("** In readRecords **");
        General  record;
        int count = 0;   //Used to populate array in while loop

        System.out.printf("%-12s%-20s%-12s\n","ID","Name","Age");
        try {
            while((record = (General) input.readObject()) != null)  {
                roster[count] = record;
                count++;
                System.out.printf("%-12d%-20s%-12d\n",record.getID(), record.getName(), record.getAge());
            }
        }
        catch(EOFException e){
            System.out.println("....catch ...." + e + "\n");
            return;
        }
        catch(ClassNotFoundException eclassNotFound){
            System.out.println("....catch ...." + eclassNotFound + "\n");
        }
        catch(IOException eIO){
            System.out.println("....catch ...." + eIO + "\n");
        }
    } 
    public void closeFile(){
        System.out.println("** In closeFile **");
        try {
            if (input != null)
                input.close();
        }
        catch(IOException ioExcetion) {
            System.err.println("Error closing file");
            System.exit(1);
        }
    }  
}
public class MergeSort {
    public void sort(General[] data, int low, int high) {
        if ((high - low) >= 1) {
            int middle1 = (low + high) / 2;
            int middle2 = middle1 + 1;

            sort(data, low, middle1);
            sort(data, middle2, high);

            merge(data, low, middle1, middle2, high);
        }
    }

    public void merge(General[] data, int left, int middle1, int middle2, int right) {
        int leftIndex = left;
        int rightIndex = middle2;
        int combinedIndex = left;
        General[] combined = new General[data.length];

        while (leftIndex <= middle1 && rightIndex <= right) {
            if(data[leftIndex].getID() <= data[rightIndex].getID()) {
                combined[combinedIndex++] = data[leftIndex++];
            }else {
                combined[combinedIndex++] = data[rightIndex++];
            }
        }
        if(leftIndex == middle2) {
            while(rightIndex <= right) {
                combined[combinedIndex++] = data[rightIndex++];
            }
        }else {
            while(leftIndex <= middle1) {
                combined[combinedIndex++] = data[leftIndex++];
            }
        }

        for(int i = left; i <= right; i++) {
            data[i] = combined[i];
        }
    }
}
public class GeneralRostersTest
{
    public static void main( String[] args )
    {
        GeneralRosters application = new GeneralRosters();
        application.openFile();
        application.readRecords();
        application.closeFile();
        application.sortRoster();
    }
}

解决方案:

你还没有检查 data[leftIndex]data[rightIndex] 对于 null 在访问它们的数据之前。

替换

if(data[leftIndex].getID() <= data[rightIndex].getID()) {
    combined[combinedIndex++] = data[leftIndex++];
}

if(data[leftIndex] != null && data[rightIndex] != null) {
    if(data[leftIndex].getID() <= data[rightIndex].getID()) {
        combined[combinedIndex++] = data[leftIndex++];
    }
}

顺便说一句,你没有检查 null 读取文件时。当没有对象可读时。input.readObject() 将返回 null 中需要检查。while 循环,使控制不进入循环体。

替换

while(true) {
    record = (General) input.readObject();

while((record = (General) input.readObject()) != null) {

本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/2877.html

(0)
上一篇 2022年6月29日 下午4:24
下一篇 2022年6月29日 下午4:24

相关推荐

发表评论

登录后才能评论