gpt4 book ai didi

java - 按字母顺序正确排序数组时出现问题

转载 作者:行者123 更新时间:2023-12-02 11:11:32 25 4
gpt4 key购买 nike

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

这是我的排序代码:

//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

最佳答案

看看compareTo javadoc 。它指出:

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

在你的行中

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

提到的“这个对象”是name[i]而“指定对象”为name[smallest] 。而你想兑换的时候 name[i] 小于 name[smallest] 。所以要么你交换 name[i]name[smallest] ,或者将比较更改为 < 0 .

此外,我始终建议在第一次测试时使用调试器逐步执行代码,尤其是在出现意外行为时。

关于java - 按字母顺序正确排序数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com