【问题标题】:Problem with the sort array with String with Java [duplicate]带有Java的String排序数组的问题[重复]
【发布时间】:2021-05-04 06:00:42
【问题描述】:

我对数组排序有一个大问题。我需要在生日年份对他进行排序,但这不起作用。你能帮我吗。我给你看我的代码。

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

【问题讨论】:

  • 请澄清。什么不起作用?排序?程序本身?
  • 特别是在这里不起作用: if (tab[j].getNaissance()
  • 错误:“二元运算符'的操作数类型错误

标签: java arrays string sorting


【解决方案1】:

if (tab[j].getNaissance() &lt; tab[indMin].getNaissance())

这是错误的。你不能像这样比较一个字符串,因为它不是一个原始的(与 int,byte,short,...相反)

要表达这一点,请使用

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

compareTo 返回 0,如果两个字符串在词法上相等,则返回正整数,如果对象在参数之后(例如 "B".compareTo("A")),否则返回负整数。

(Doc)

【讨论】:

  • 好的,我会试试这个。谢谢
  • 非常感谢。我在 1 周内搜索以找到解决方案。真的谢谢你!
  • 如果我能帮助你,请考虑accepting我的回答
  • 我已经做到了
猜你喜欢
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多