java - 使用 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
解决方案
您收到编译错误的原因是因为您String name
在尝试使用它之前从未设置过值。
您应该像在您的描述中那样传递值addSort(String name)
。这将消除该错误。
我看不出你String
在函数中返回的原因。此函数似乎也没有添加传入的名称。
推荐阅读
- angular - 如何在 Angular 服务中直接使用 .subscribe?
- string - 使用空接口更改函数中的 arg
- microsoft-teams - 文件上传失败 MSTeams
- javascript - 发布请求在 Postman 和 cURL 中有效,但在 Angular 中无效
- javascript - 如何在自定义导航菜单中正确使用点击事件?
- sql - SQL查询查找每个用户的活动时间
- python - Plotly:如何摆脱多余的 xaxis 刻度?
- moodle - R/exams:exams2moodle 的开放式问题
- php - laravel 和 guzzle 身份验证
- azure - Azure kubernetes - Nginx 控制器的数量?