Pages

Minggu, 30 Oktober 2011

Sequential Search Object

Kelas Larik

package search;

public class Larik {

    public static int sequentialSearch(Object[] data, Object cari) {
        for (int i = 0; i < data.length; i++) {

            if (((Comparable) data[i]).compareTo(cari) == 0) {
                return i;
            }
        }
        return -1;
    }
}


Kelas Comparable(Interface)


package search;

public interface comparable {
   int compareTo(Object o);
}



Kelas Mahasiswa
package search;

public class Mahasiswa implements Comparable<Object>{

    private int nim;
    private String nama;
   
    public int getNim() {
        return nim;
    }

    public void setNim(int nim) {
        this.nim = nim;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }
   
       public int compareTo(Object o) {
//        if (nim == ((Mahasiswa) o).nim) {
//            return 0;
//        } else if (nim < ((Mahasiswa) o).nim) {
//            return -1;
//        } else {
//            return 1;
//        }

            return nama.compareTo(((Mahasiswa)o).getNama());
    }
}




Kelas Main


package search;

public class mainLarikObject {
    public static void main(String[] args) {
        Mahasiswa mhs[] = new Mahasiswa[3];
        mhs [0] = new Mahasiswa();
        mhs[0].setNim(10212);
        mhs[0].setNama("roy");

        mhs [1] = new Mahasiswa();
        mhs[1].setNim(11666);
        mhs[1].setNama("ryu");

        mhs [2] = new Mahasiswa();
        mhs[2].setNim(12301);
        mhs[2].setNama("rya");

        Mahasiswa cariMhs = new Mahasiswa();
        cariMhs.setNama("sooni");

        int hasil=Larik.sequentialSearch(mhs, cariMhs);
        if (hasil >= 0){
            System.out.println("data ditemukan di index ke "+ hasil);
            System.out.println("Nim     : "+mhs[hasil].getNim());
            System.out.println("Nama    : "+mhs[hasil].getNama());}
        else
        System.out.println("Data dengan Nama " + cariMhs.getNama()+" tidak ketemu");
    }
   



}

0 komentar:

Posting Komentar