为什么我的排序循环似乎附加了一个不应该的元素? [英] Why does my sorting loop seem to append an element where it shouldn't?

查看:179
本文介绍了为什么我的排序循环似乎附加了一个不应该的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to sort an array of Strings using compareTo(). This is my code:

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

我收到的结果,但不是我想得到的结果,这是:

I am getting results, but not the results I want to get, which are:

Hello This Example Is Sorting

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

How can I adjust my code to sort the string array properly?

推荐答案

您的输出是正确的。在开头表示Hello和This的白色字符。

Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.

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

Another issue is with your methodology. Use the Arrays.sort() method:

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

输出:

 Hello
 This
Example
Is
Sorting

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

Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.

这篇关于为什么我的排序循环似乎附加了一个不应该的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆