-2

I have a big problem for sort an array. I need to sort him in function the years of birthday but it's don't work. can you help me please. I show you my code.

class Personne {

    private String nom;
    private String naissance; //format "jj/mm/aaaa"
    private int nbCafe; //nb de tasses de café consommé par jour

    public Personne(String nom, String naissance, int nbCafe) {
        this.nom = nom;
        this.naissance = naissance;
        this.nbCafe = nbCafe;
    }

    public Personne(String nom, String naissance) {
        this.nom = nom;
        this.naissance = naissance;
        this.nbCafe = 1;
    }

    public String getNaissance() {
        return this.naissance;
    }

    public void setNaissance(String naissance2) {
        this.naissance = naissance2;
    }

    public String toString() {
        return this.naissance;
    }

}
public class Tp2NumeroA {
    public static void trierTableau(Personne[] tab) {
        
        for (int i = 0; i < tab.length-1; i++) {
            int indMin = i;
            for(int j = i+1; j < tab.length; j++) {
                if (tab[j].getNaissance() < tab[indMin].getNaissance()) {
                    indMin = j;
                }
            }
            
            if (indMin != i) 
            {
                Personne tempo = tab[i];
                tab[i] = tab[indMin];
                tab[indMin] = tempo;
            }
        }
        System.out.println("    Indice    Tableau pers");
        System.out.println("------------------------------------------------");
        
        for (int i=0; i<tab.length; i++) {
            System.out.printf("      %d)      %s\n", i, tab[i]);
        }
    }

    public static void main(String[] args) {
        Personne[] tabPeople = new Personne[5];
        
        tabPeople[0] = new Personne("Jo", "16/11/1992", 2);
        tabPeople[1] = new Personne("Paul", "02/05/1990");
        tabPeople[2] = new Personne("Lucie", "23/05/1990", 5);
        tabPeople[3] = new Personne("Bob", "19/02/1985", 0);
        tabPeople[4] = new Personne("Carole", "30/06/1991", 2);

        trierTableau(tabPeople);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Whynotzer
  • 1
  • 1

1 Answers1

0

if (tab[j].getNaissance() < tab[indMin].getNaissance())

This is wrong. You can't compare a string like this, as it is not a primitive (As opposed to int,byte,short,...)

To express this, use

if (tab[j].getNaissance().compareTo(tab[indMin].getNaissance()) < 0) {
   ...

compareTo returns 0, if both strings are lexically equals, a positive integer, if the object is after the argument (E.g. "B".compareTo("A")), otherwise an negative integer.

(Doc)

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29