java - java根据desc中的位置对名称进行排序
问题描述
从用户那里获取 n 个名称和位置,并根据位置对名称进行降序排序
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name[] = new String[5];
String location[] = new String[5];
for (int i = 0; i < name.length; i++) {
System.out.println("enter the name");
name[i] = sc.nextLine();
System.out.println("enter the location");
location[i] = sc.nextLine();
}
Arrays.sort(location, Collections.reverseOrder()); //desc
System.out.println("Name and location:");
System.out.println(name[0] + " " + location[0]);
System.out.println(name[1] + " " + location[1]);
System.out.println(name[2] + " " + location[2]);
System.out.println(name[3] + " " + location[3]);
System.out.println(name[4] + " " + location[4]); /*here the names are not changed but the locations are comes with sorted order so the names and locations are mis matched. could you please help me?*/
}
}
解决方案
您将名称和位置存储在两个不同的数组中。然后,您只需反转包含该位置的数组的顺序。最快的解决方法是反转包含名称的数组的顺序:
Arrays.sort(name, Collections.reverseOrder()); // desc name too
但总的来说,将信息存储在两个不同的数组中并通过相信数组的顺序相同来“匹配”它是一种不好的做法。您可能需要考虑改用Map或构建一个自定义对象来存储名称和位置,然后将该对象放入数组或列表中。
推荐阅读
- html - 将静态 html 页面与 Angular 6+ 混合
- python - 转换与 Python 中另一个工具箱兼容的符号变量的 type()
- c++ - vulkan.hpp 绑定生成 WinAPI 错误
- javascript - CMYK 颜色格式 wColorPicker.js
- javascript - How to handle a few TextInput by single handler in React Native without lambda function?
- python - 如何修复包含有效后续兄弟路径的 XPATH 的“不支持的定位器策略”?
- android - 在 Android 应用中使用 Firebase 将登录集成到 Window 时出现错误
- html - 是否有一个下拉组件允许在桌面上自定义样式选项,但在移动设备上允许本机行为?
- docker - 嵌套文件夹中带有 cloudbuild.yaml 的 Cloud Build - 构建失败
- docker - 如何检查 DockerHub 上用于自动构建的 Docker 版本?