按字母顺序正确排序数组的麻烦

时间:2018-05-29 10:19:33

标签: java arrays sorting

我的部分代码出现问题。它必须按字母顺序按名称排序,但似乎是以降序方式进行排序。有人可以指导我应该做出哪些更改,以便输出正确显示数据?谢谢。

这是我的分类代码:

//Method sortName
            public static void sortName() throws IOException {

            //Selection Sort
            for (x = 0; x < 8; x++) {
                smallest = x;

            for(i = x + 1; i < 8; i++) {

                //Compare current smallest
                //to the current position in the array
                if(name[i].compareTo(name[smallest])> 0) {
                    smallest = i;
                }

            }
                //Swap smallest element with position in array      
                temp = name [x];
                name [x] = name [smallest];
                name [smallest] = temp;

                temp = crime [x];
                crime [x] = crime [smallest];
                crime [smallest] = temp;

                temp = year [x];
                year [x] = year [smallest];
                year [smallest] = temp;

            }
            //Display each category of records; names, crime, year
            System.out.print("Name" + " ----" + "Crime" + "----" + "Year\n");

            //output
            for (x = 0; x < 8; x++) {

                //Display each sorted criminal name with the crime and year. 
                System.out.println(name[x] + " --- " + crime[x] + " --- " + year[x]);

这是我的输出:

Name ----Crime----Year
Slippery Sal --- Arson --- 1997
Natasha Ora --- Theft --- 2007
Kate Olaf --- Assault --- 1984
Eddie Striker --- Arson --- 1978
Bugs Malone --- Theft --- 1981
Bob Allen --- Assault --- 1957
Anne Wilson --- Arson --- 2013

1 个答案:

答案 0 :(得分:1)

查看compareTo javadoc。它声明:

  

返回:       一个负整数,零或正整数,因为此对象小于,等于或大于指定的对象。

在你的行

if(name[i].compareTo(name[smallest])> 0) {

提到的“此对象”为name[i],“指定对象”为name[smallest]。如果name[i] 少于 name[smallest],您希望进行交换。因此,您要么交换name[i]name[smallest],要么将比较更改为< 0

另外,我总是建议在第一次测试时逐步使用调试器执行代码,特别是在出现意外行为时。