Help with the task: Enter three lines from the keyboard. Arrange and display lines in ascending order of their length.

  • If you are allowed to deal with arrays, then you can declare an array of three strings and sort it. - Vlad from Moscow

1 answer 1

You would try to write something yourself first, the task is trivial.

Code:

public static void main(String[] args){ String[] arr = new String[3]; Scanner in = new Scanner(System.in); //Π’Π²ΠΎΠ΄ΠΈΠΌ значСния Π² массив (вмСсто массива Π»ΡƒΡ‡ΡˆΠ΅ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ ΠΊΠΎΠ½Π΅Ρ‡Π½ΠΎ ΠΆΠ΅ //Π΄ΠΈΠ½Π°ΠΌΠΈΡ‡Π΅ΡΠΊΡƒΡŽ структуру Π΄Π°Π½Π½Ρ‹Ρ… (Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ ArrayList): for(int i = 0; i < 3; i++){ arr[i] = in.nextLine(); } //Π—Π΄Π΅ΡΡŒ происходит сортировка (сортировка ΠΏΡƒΠ·Ρ‹Ρ€ΡŒΠΊΠΎΠΌ): for(int i = arr.length-1 ; i > 0 ; i--){ for(int j = 0 ; j < i ; j++){ /*Π‘Ρ€Π°Π²Π½ΠΈΠ²Π°Π΅ΠΌ элСмСнты ΠΏΠΎΠΏΠ°Ρ€Π½ΠΎ, Ссли ΠΎΠ½ΠΈ ΠΈΠΌΠ΅ΡŽΡ‚ Π½Π΅ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½Ρ‹ΠΉ порядок, Ρ‚ΠΎ мСняСм мСстами */ if( arr[j].length() > arr[j+1].length() ){ String tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } //Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ Π½Π° экран: for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } } 

You can also use the sort method if you want to sort in alphabetical order:

 //Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ массива Arrays.sort(arr); //Π²Ρ‹Π²ΠΎΠ΄ Π½Π° экран