首页 > 解决方案 > 使用 compareTo() 按字母顺序对名称数组进行排序

问题描述

我试图通过使用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

标签: java

解决方案


您收到编译错误的原因是因为您String name在尝试使用它之前从未设置过值。

您应该像在您的描述中那样传递值addSort(String name)。这将消除该错误。

我看不出你String在函数中返回的原因。此函数似乎也没有添加传入的名称。


推荐阅读