package com.javarush.test.level10.lesson11.home09; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /* Одинаковые слова в списке Ввести с клавиатуры в список 20 слов. Нужно подсчитать количество одинаковых слов в списке. Результат нужно представить в виде словаря Map<String, Integer>, где первый параметр – уникальная строка, а второй – число, сколько раз данная строка встречалась в списке. Вывести содержимое словаря на экран. В тестах регистр (большая/маленькая буква) влияет на результат. */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); ArrayList<String> words = new ArrayList<String>(); for (int i = 0; i < 20; i++) { words.add(reader.readLine()); } Map<String, Integer> map = countWords(words); for (Map.Entry<String, Integer> pair : map.entrySet()) { System.out.println(pair.getKey() + " " + pair.getValue()); } } public static Map<String, Integer> countWords(ArrayList<String> list) { HashMap<String, Integer> result = new HashMap<String, Integer>(); for (int z = 0; z<list.size();z++ ){ String temp = list.get(z); int kol = 1; if (list.size()>1) { for (int b = z + 1; b < list.size(); ) { String temp2 = list.get(b); if (temp2.equals(temp)) { kol++; } else b++; } } result.put(temp, kol); } return result; } } - fourNothing is clear, that where something does not allow to enter. And still it is necessary to think and use HashMap for the intended purpose. - Qwertiy ♦
- the program should take 20 lines and output the result, but for some reason I don’t accept string reception is not limited to 20 - Nikolay
- ArrayList <String> words = new ArrayList <String> (); for (int i = 0; i <20; i ++) {words.add (reader.readLine ()); } - Nikolai
- Yes? And where is it not limited? ideone.com/tXebai - the 21st word is not listed. - Qwertiy ♦ 7:38 pm
- @Qwertiy if I enter two identical lines, the program hangs, a snag in equals, I can not understand how it affects the hang. ideone.com/ULuHAy - Nikolay
|