gpt4 book ai didi

java - 为什么我的排序循环似乎在不应该的地方附加了一个元素?

转载 作者:IT老高 更新时间:2023-10-28 13:51:03 26 4
gpt4 key购买 nike

我正在尝试使用 compareTo() 对字符串数组进行排序。这是我的代码:

static String Array[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
String temp;

public static void main(String[] args)
{

for (int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if (Array[i].compareTo(Array[j])<0)
{
String temp = Array[j];
Array[j] = Array[i];
Array[i] = temp;
}
}
System.out.print(Array[j]);
}
}

现在的输出是:

Hello  This Example Sorting is

我得到了结果,但不是我想要得到的结果,它们是:

Hello This Example Is Sorting

如何调整我的代码以正确排序字符串数组?

最佳答案

你的输出是正确的。表示开头的“Hello”和“This”的白色字符。

另一个问题是您的方法。使用 Arrays.sort() 方法:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

输出:

 Hello
This
Example
Is
Sorting

这里数组“is”的第三个元素应该是“Is”,否则排序后会排在最后。因为 sort 方法内部使用 ASCII 值对元素进行排序。

关于java - 为什么我的排序循环似乎在不应该的地方附加了一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986386/

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