/
alim4ik-had
/
SberJavaCourseBeginner
Обзор
Документация
Войти
/
alim4ik-had
/
SberJavaCourseBeginner
Код
Запросы
2
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
hw3/task1/WordRating.java
49 строк
2 KB
alimo
hw3_task1
15 мар 2025, 21:17
15 мар 2025, 21:17
3c58dbb
Код
Авторство
О чём код?
package hw3.task1; import java.util.*; public class WordRating { public static void main(String[] args) { String[] inputTextArray = getInputText().split(" "); countNumberWords(inputTextArray); } private static String getInputText(){ Scanner sc = new Scanner(System.in); System.out.println("Введите текст для определения рейтинга слов:"); return sc.nextLine(); } private static void countNumberWords(String[] array){ Map<String, Integer> countWords = new LinkedHashMap<>(); for(String word : array){ countWords.put(changeWord(word), countWords.getOrDefault(changeWord(word), 0)+1); } descSort(countWords); ascSort(countWords); } private static String changeWord(String word){ return word.toLowerCase().replaceAll("\\p{Punct}+|\\p{Punct}+$", ""); } private static void ascSort(Map<String, Integer> words){ List<Map.Entry<String, Integer>> pairKeyValue = new ArrayList<>(words.entrySet()); Collections.sort(pairKeyValue, Map.Entry.comparingByValue()); outputRating(pairKeyValue, "редко"); } private static void descSort(Map<String, Integer> words){ List<Map.Entry<String, Integer>> pairKeyValue = new ArrayList<>(words.entrySet()); Collections.sort(pairKeyValue, Map.Entry.comparingByValue(Comparator.reverseOrder())); outputRating(pairKeyValue, "часто"); } private static void outputRating(List<Map.Entry<String, Integer>> pairKeyValue, String ratingType){ int length = 5; if(pairKeyValue.size() < 5) length = pairKeyValue.size(); System.out.println("Топ "+ length + " "+ ratingType + " встречаемых слов (Формат вывода: 'слово' - 'количество'):"); for (int i = 0; i < length; i++){ System.out.println(pairKeyValue.get(i).getKey() + " - " + pairKeyValue.get(i).getValue()); } } }