排序10个字母的字母顺序

时间:2015-10-16 08:33:27

标签: java

我是10年级并且正在努力学习。我需要一个按字母顺序排序10个单词的程序。我的程序不起作用,它抛出最后一个单词,如果word1用a开头,word2用d开头,word3用b开头,word4用c开头,它把word2抛出,打印word3 2次。

String word1, word2, word3, word4, word5, word6, word7, word8, word9, word10;
  word1 = "apple";
  word2 = "banana";
  word3 = "jelly";
  word4 = "jam";
  word5 = "Thandi";
  word6 = "Thomas";
  word7 = "hi";
  word8 = "Hi";
  word9 = "someone";
  word10 = "some-one";

   if (word1.compareTo(word2) <0)
  {
     System.out.print(word1);
  }
   else 
  {
     System.out.print(word2);
  }

1 个答案:

答案 0 :(得分:0)

public static void main(String[ ] args)
 {
         String[ ] names = {"apple","banana","jelly","jam","Thandi","Thomas","hi","Hi","someone","some-one"}; //This line creates an array and adds your values in to the created array
         sortStringExchange (names); //the method below is called
         for ( int k = 0;  k < names.length;  k++ )
            System.out.println( names [ k ] );      // prints all the values in the array in ascending order
  }

  public static void sortStringExchange( String  x [ ] )
  {
        int i, j;
        String temp;

        for ( i = 0;  i < x.length - 1;  i++ )
        {
            for ( j = i + 1;  j < x.length;  j++ )
            { 
                     if ( x [ i ].compareToIgnoreCase( x [ j ] ) > 0 )
                      {                                             // ascending sort
                                  temp = x [ i ];
                                  x [ i ] = x [ j ];    // swapping
                                  x [ j ] = temp;

                       }
               }
         }
  } 

这是更简单的方式

String[] strings = { "apple","banana","jelly","jam","Thandi","Thomas","hi","Hi","someone","some-one" };
Arrays.sort(strings);

请阅读here

中的数组