java - 使用compareTo()按字母顺序对名称数组进行排序

标签 java

我试图使用 compareTo() 和方法 String addSort(String name) 按字母顺序对名称数组进行排序,但在编译时出现错误“返回名称”行,表示我的“变量“名称”可能尚未初始化”(当它已经初始化时)。

我已经制作了按字母顺序排序的方法和代码,我认为在使用compareTo()作为数组排序方式时应该是正确的。 (数组“moreFriends”是一个新数组,当它变满时,它将原始数组“friends”的大小加倍)(注意这不是全部代码)

public class SimpleDataStructure{

    private String [] friends;
    private String [] moreFriends;
    private int counter;

    public SimpleDataStructure()
    {
        friends= new String[5];
        counter=0;
    }
public String addSort(){
        String name;
        for(int i = 0; i < moreFriends.length; i++){

            for(int j = i + 1; j < moreFriends.length; j++){

                if(moreFriends[i].compareTo(moreFriends[j]) > 0){
                    String temp = moreFriends[i];
                    moreFriends[i] = moreFriends[j];
                    moreFriends[j] = temp;
                }
            }
        }
        System.out.println("Names in sorted order:");
        for(int i = 0; i < moreFriends.length -1; i++){
            System.out.println(moreFriends[i]);   
        }
        return name;   
    }
public static void main( String [] arg){
SimpleDataStructure sortedfriends = new SimpleDataStructure();
        System.out.println(sortedfriends.addSort(name));
}

这是我尝试编译程序时收到的错误消息:

SimpleDataStructure.java:85: error: variable name might not have been initialized
        return name;
               ^
1 error

当我期望输出最终是:

(unsorted)
Kalle
Bob
Carl
Alice
Lewis

(sorted) 
Alice
Bob
Carl
Kalle
Lewis

最佳答案

您需要像这样声明您的函数:

public String addSort(String name){

并删除字符串声明:

String name;

并且你没有为名称赋予值(value)。

您可以使用以下方法解决您的问题:

String [] a="a","v","b";
Arrays.sort(a);

关于java - 使用compareTo()按字母顺序对名称数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521723/

相关文章:

java - 无法解决方法 getResource().getColor() 错误

java - AppEngine 上的循环日志是否基于条目数量或条目大小?

java - 为什么我的构造函数中出现 StackOverflowError 异常

java - 如何从java中的axis2 webservice请求获取客户端的ip?

java - 需要 TRIPLE_DOT,发现为 ';'

java - 如何在 cucumber 中的特征背景 "Given"语句中传递变量?

java - 如何从日期格式中获得最低的计时单位?

java - 如何让我的数组正确排序?递归排序

java - JUnit java.net.ConnectException

java - 从 Java 8 中的对象列表中获取多个属性列表