Hello!

It is necessary to solve the following problem

Enter N lines. Arrange and display lines in ascending order of their length values. If the lengths of the lines are the same, sort them in lexicographical order.

Wrote code to arrange strings.

Question: how to implement the output of the same length of lines in a lexicographical order I can not understand.

public static void task2() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); String[] strings = new String[n]; //Считываем строки for (int i = 0; i < strings.length; i++) { strings[i] = reader.readLine(); } //Сортировка массива методом пузырька for (int i = strings.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (strings[j].length() > strings[j + 1].length()) { String max = strings[j]; strings[j] = strings[j + 1]; strings[j + 1] = max; } } } //Вывод элементов массива for (int i = 0; i < strings.length; i++) { System.out.println("(" + strings[i].length() + ")" + ":" + " " + "\"" + strings[i] + "\""); } } 

    1 answer 1

     String.compareTo(String) 

    Probably what you are looking for. Compares strings lexicographically, returns an integer, 0 if the strings are equal,> 0, if this string is greater, and <0, if this string is less than the argument.

    Just keep in mind that this method gives priority to lexicography, rather than length, and if you want to prioritize length, then compare the length separately and before lexicography.

    PS You can use ArrayList or LinkedList , and use the sort method to sort :

     myList.sort((s1, s2) -> { if(s1.length != s2.length) return s1.length - s2.length; else return s1.compareTo(s2); });