gpt4 book ai didi

java - Java 中的快速排序(比较)

转载 作者:行者123 更新时间:2023-11-30 07:43:57 26 4
gpt4 key购买 nike

<分区>

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

抽象类

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());
}
}
}

输出

Exception in thread "main" java.lang.NullPointerException
at SortingObject.Mahasiswa.compareTo(Mahasiswa.java:33)
at SortingObject.Larik.BubbleSort(Larik.java:16)
at SortingObject.Main.main(Main.java:24)
C:\Users\Yeski's Legion\AppData\Local\NetBeans\Cache\8.2\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com