Advertisement
Sakol

Done! Sorting by the number of words per line.

Jan 22nd, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class ForMens {
  4.  
  5.     public String[] mas;
  6.     private char[] separators = { '.', ',', ' ' };
  7.     int[] res;
  8.  
  9.     public void createMas() {
  10.         int n = 0;
  11.         Scanner sc = new Scanner(System.in);
  12.         System.out.print("Введите количество строк: ");
  13.  
  14.         if (sc.hasNextInt()) {
  15.             n = sc.nextInt();
  16.         } else {
  17.             System.out.print("Введены некорректные данные!");
  18.             return;
  19.         }
  20.         if (n <= 10) {
  21.             mas = new String[n];
  22.             Scanner sc1 = new Scanner(System.in);
  23.             for (int i = 0; i < mas.length; i++) {
  24.                 System.out.print("Введите строку номер " + (i + 1) + ": ");
  25.                 mas[i] = sc1.nextLine();
  26.             }
  27.         }
  28.     }
  29.  
  30.     private boolean isSeparator(char symbol) {
  31.         for (int i = 0; i < separators.length; i++) {
  32.             if (separators[i] == symbol) {
  33.                 return true;
  34.             }
  35.         }
  36.         return false;
  37.     }
  38.  
  39.     public int countWords(String line) {
  40.         boolean insideWord = false;
  41.         int result = 0;
  42.         for (int i = 0; i < line.length(); i++) {
  43.             if (!isSeparator(line.charAt(i))) {
  44.                 if (!insideWord) {
  45.  
  46.                     result++;
  47.                     insideWord = true;
  48.                 }
  49.             } else {
  50.  
  51.                 insideWord = false;
  52.             }
  53.         }
  54.         return result;
  55.     }
  56.  
  57.     public void sorting() {                      // вот тут уже на основе твоих методов я сделал сортировку массива строк
  58.         res = new int[mas.length];               // ну и слегка изменил синтаксис твой, потому что кое что видимо в Java по-другому
  59.         for (int i = 0; i < mas.length; i++) {
  60.             res[i] = countWords(mas[i]);
  61.         }
  62.         for (int i = 0; i < mas.length; i++) {
  63.             for (int j = i + 1; j < mas.length; j++) {
  64.                 if (res[i] > res[j]) {
  65.                     String temp = mas[i];
  66.                     mas[i] = mas[j];
  67.                     mas[j] = temp;
  68.                 }
  69.             }
  70.         }
  71.  
  72.     }
  73.  
  74.     public void showMas() {
  75.         for (int i = 0; i < mas.length; i++) {
  76.             System.out.println(mas[i]);
  77.  
  78.         }
  79.     }
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement