0

如何比较 3 个字符串,然后按字母顺序排列?因此,如果参数是“Berry”、“alex”、“cory”,您将返回一个带有“alex, Berry, cory”的字符串。(java)我使用比较并找到了第一个字母,但由于某种原因(我做错的事情)也不起作用

我的程序如何修复?

   public String CW4J( String A, String B, String C )
{ 
  /// format will be like this  A+","+B+","+C
  String TEMP;
  String firstLetter  = "";
  String secondletter  = "";
  String thirdletter  = "";
  firstLetter = String.valueOf(A.charAt(0));
  secondletter = String.valueOf(B.charAt(0));
  thirdletter = String.valueOf(C.charAt(0));
  
  for(int i = 0; i < 100; i++){
  int compare = firstLetter.compareTo(secondletter);  
  if (compare < 0) {  
    TEMP = B;
    B = A;
    A = TEMP;
  } else if (compare > 0) {
    TEMP = A;
    A = B;
    B = TEMP;
  }
  
  compare = thirdletter.compareTo(secondletter);  
  if (compare < 0) {  
     TEMP = B;
    B = C;
    C = TEMP;
  } else if (compare > 0) {
    TEMP = C;
    C = B;
    B = TEMP;
  }
  
   compare = firstLetter.compareTo(thirdletter);  
  if (compare < 0) {  
    TEMP = C;
    C = A;
    A = TEMP;
  } else if (compare > 0) {
    TEMP = A;
    A = C;
    C = TEMP;
  }}
  return A+","+B+","+C;
}
4

3 回答 3

4

更好:

  • 将每个字符串添加到列表
  • 排序列表
  • 将琴弦连接在一起

这将适用于超过 3 个字符串,而不会产生大量比较。

请尝试以这种方式实施它,并用您遇到的任何问题更新您的问题。

于 2020-12-21T22:04:48.847 回答
1

您可以创建一个List<String> list 字符串,然后将其排序为Collections.sort(list, String.CASE_INSENSITIVE_ORDER). 最后, list#toString会给你你正在寻找的字符串。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("Berry", "alex", "cory"));
        Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
        String result = list.toString();
        System.out.println(result);
    }
}

输出:

[alex, Berry, cory]
于 2020-12-21T22:23:05.493 回答
0

尝试这个

   String temp, allNames = "";
   String []names = {"Berry","alex","cory"};
   for (int i = 0; i < 3; i++) 
   {
        for (int j = i + 1; j < 3; j++) 
        {
            if (names[i].compareToIgnoreCase(names[j])>0) 
            {
               temp = names[i];
               names[i] = names[j];
               names[j] = temp;
            }
        }
      allNames += names[i] + ",";
   }
   System.out.print("Names : " + allNames);

于 2020-12-22T08:12:09.370 回答