Java中的快速排序(比较)

时间:2018-10-21 09:58:19

标签: java nullpointerexception quicksort compareto

该程序无法运行,但我不知道为什么:

抽象类

public class Mahasiswa implements Comparable {

    private String nama;
    private int nim;

    public Mahasiswa(String nama, int nim) {
    }
    public String getNama() {
        return nama;
    }
    public int getNim() {
        return nim;
    }
    public void setNama() {
        this.nama=nama;
    }
    public void setNim() {
        this.nim=nim;
    }

    @Override
    public int compareTo(Object o) {
        Mahasiswa key = (Mahasiswa) o;
        if (this.nama.compareTo(key.getNama()) == 0) {
            return -1;
        }else if (this.nama.compareTo(key.getNama()) > 0) {
            return 1;
        }else{
            return 0;
    }
    }
}

方法类:

        public static Mahasiswa[] BubbleSort(Object[] object) {
        Mahasiswa[] data =(Mahasiswa[]) object;
        for (int i = 1; i < data.length; i++) {
            for (int j = 0; j < data.length - i; j++) {
                if (((Comparable)data[j]).compareTo(data[j+1]) ==1 ) {
                    Mahasiswa c = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = c;
                }
            }
        }
        return data;
    }

主班

    public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Mahasiswa[] data = {new Mahasiswa("Karel", 175314105),
        new Mahasiswa("Fandur", 175314006),
        new Mahasiswa("Yeski", 1753141104),
        new Mahasiswa("Tiosu", 175314001),
        new Mahasiswa("Jono", 175314090)};

        Larik.BubbleSort(data);

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

输出

  

线程“主”中的异常java.lang.NullPointerException
  在SortingObject.Mahasiswa.compareTo(Mahasiswa.java:33)
  在SortingObject.Larik.BubbleSort(Larik.java:16)
  在SortingObject.Main.main(Main.java:24)
  C:\ Users \ Yeski的Legion \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-   snippets \ run.xml:53:Java返回:1
  失败(总时间:0秒)

1 个答案:

答案 0 :(得分:3)

您必须将实例变量值设置为构造函数或setter,否则它将为null。

public Mahasiswa(String nama, int nim) {
  this.nama = nama;
  this.nim = nim;
}

您还可以使用setter方法。