如何对数组中的字符串进行排序?升/降

时间:2017-05-23 12:48:54

标签: java

Scanner input = new Scanner(System.in);
String[] string_array = new String[5];

for (int i = 0; i < string_array.length; i++)
{
    System.out.println("Please enter a string to sort:");
    string_array[i] = input.next();
}

System.out.println ("\nSorting options:\nA.Ascending\nB.Descending\n\nPlease enter your choice in specific letter:");
Scanner s = new Scanner (System.in);
String a = s.next();

if (a.equals("a")){
    Arrays.sort(args);
    System.out.println ();
    for(int i = 0; i < string_array.length; i++)
        System.out.println(string_array[i]);

1 个答案:

答案 0 :(得分:0)

    Scanner input = new Scanner(System.in);
    String[] string_array = new String[5];

    for (int i = 0; i < string_array.length; i++)
    {
        System.out.println("Please enter a string to sort:");
        string_array[i] = input.next();
    }

    System.out.println ("\nSorting options:\nA.Ascending\nB.Descending\n\nPlease enter your choice in specific letter:");
    Scanner s = new Scanner (System.in);
    String a = s.next();

    if (a.equalsIgnoreCase("a")){
        //I think this should be passed into string_array
        Arrays.sort(string_array);
    }else if(a.equalsIgnoreCase("b")){
        Arrays.sort(string_array, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
    }
    System.out.println ();
    for(int i = 0; i < string_array.length; i++)
        System.out.println(string_array[i]);
}