我是Java的新手,但是为了扩展我的知识。以下是我很难完成的课堂作业。我需要创建一个传递二维字符串数组的方法,然后按第二个元素对数组进行排序。

方法sortContacts()


声明为公共静态方法,应采用
二维String数组作为参数,并且为
数组中的联系人数量
不返回任何内容o对给定的联系人列表的内容进行排序
作为参数,使用lastName作为排序字段
您可以使用文本中描述的任何排序机制
(气泡,插入或选择)
关键概念:实施排序时,诀窍是
确定要比较的值的尺寸,并
它们如何与循环中的值相关。
提示:
请勿依赖数组长度来循环,而应使用
接触数的价值
您的临时变量将是
    大小为3的数组,String[] temp = new String[3];
您将需要
        使用string1.compareTo(string2)方法比较两个字符串。


样本数据:(名字,姓氏,电话号码)

String [][] contactsArray = {

        {"Emily","Watson","913-555-0001"},
        {"Madison","Jacobs","913-555-0002"},
        {"Joshua","Cooper","913-555-0003"},
        {"Brandon","Alexander","913-555-0004"},
        {"Emma","Miller","913-555-0005"},
        {"Daniel","Ward","913-555-0006"},
        {"Olivia","Davis","913-555-0007"},
        {"Isaac","Torres","913-555-0008"},
        {"Austin","Morris","913-555-0009"}



public static void sortContact(String[][] contactsArray, int numContacts) {

    String[] temp = new String[3];
    String [] words = contactsArray[3];

    for(int i = 0; i < numContacts-1; i++)
    {
        int smallest = i;
        for(int j = i + 1; j < numContacts-1; j++)
        {

            //Prints loop variables so I can see them before any action
            System.out.println("First: "+words[j]+" " +"Second "+words[i]);
            if(words[j].compareTo(words[i]) < 0)
                smallest = j;
        }

       //put the new minimum in the i-th position.

        //String temp = words[i];
        words[i] = words[smallest];
        words[smallest] = temp[i];
    }
}


整数数组有很多示例,而字符串数组有很多示例,

任何建议表示赞赏。

最佳答案

您可以这样做:

 for(int i=0;i<numContacts;i++) {
        for(int j=i+1;j<numContacts;j++) {
            if(contactsArray [i][1].compareTo(contactsArray [j][1])>0) {
                String[] temp = contactsArray [i];
                contactsArray [i] = contactsArray [j];
                contactsArray [j] = temp;
            }
        }
  }

10-06 05:43
查看更多