首页 > 解决方案 > 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?*/
    }
}

标签: javaarraysstringsorting

解决方案


您将名称和位置存储在两个不同的数组中。然后,您只需反转包含该位置的数组的顺序。最快的解决方法是反转包含名称的数组的顺序:

Arrays.sort(name, Collections.reverseOrder()); // desc name too

但总的来说,将信息存储在两个不同的数组中并通过相信数组的顺序相同来“匹配”它是一种不好的做法。您可能需要考虑改用Map或构建一个自定义对象来存储名称和位置,然后将该对象放入数组或列表中。


推荐阅读