Task :

The only line contains the text. For each word in this text, calculate how many times it has been encountered in this text before.
A word is a sequence of non-blank characters in a row, words separated by one or more spaces or line breaks.

My decision course:

We read a string from the keyboard, determine how many words are in a string, create an array of type String . The length of the array is equal to the number of words in the string. In the array indices save each word. After we compare all the elements with each other and keep a counter.

My code is:

 import java.util.Scanner; public class Semnadcat1 { public static void main(String[] args) { System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ тСкст"); Scanner in = new Scanner(System.in); String s = in.nextLine(); int a = s.split(" ").length; int i; String[] b = new String[a]; for (i = 0; i < a; i++) { for (String retval : s.split(" ")) { b[i] = retval; System.out.println(b[i]); } } } } 

Errors:

Cannot put words into array elements.

  • слова Ρ€Π°Π·Π΄Π΅Π»Π΅Π½Ρ‹ ΠΎΠ΄Π½ΠΈΠΌ ΠΈΠ»ΠΈ большим числом ΠΏΡ€ΠΎΠ±Π΅Π»ΠΎΠ² ΠΈΠ»ΠΈ символами ΠΊΠΎΠ½Ρ†Π° строки "Π°Π°Π° Π±Π±Π±".split(" ").length - see what is "Π°Π°Π° Π±Π±Π±".split(" ").length . - post_zeew
  • Eh, the parser gaps ate. In general, put between the words not one space, but more. - post_zeew
  • Look at your code (in particular, the nested loop) and think about what you are doing: at each iteration "i" you assign the i-th cell of the array "a" to different values. Think again. You can rewrite your code in a dozen different ways, but without an understanding of your code there will be no sense from any of them. - AseN
  • @ 0xFFh Well, tell me what needs to be corrected, I don’t understand much, send in the right direction ( - Marat Zimnurov

2 answers 2

The split method returns an array of String (words in this case), so there is no need to manually add words to the array.
To simplify counting the number of occurrences of each word, you can store word-number pairs in a HashMap .

 public static void main(String[] args) { System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ тСкст"); Scanner in = new Scanner(System.in); String string = in.nextLine(); String[] words = string.split("\\s+"); HashMap<String, Integer> wordToCount = new HashMap<>(); for (String word : words) { if (!wordToCount.containsKey(word)) { wordToCount.put(word, 0); } wordToCount.put(word, wordToCount.get(word) + 1); } for (String word : wordToCount.keySet()) { System.out.println(word + " " + wordToCount.get(word)); } } 

split is also made for "one or more whitespace characters" using a regular expression, which helps to avoid problems with empty words due to consecutive spaces.

  • Everything works fine) is a very interesting code) - Marat Zimnurov
  • rather, the usual, standard - AseN

Option with streams:

 String text = "text hello text"; String word = "text"; long count = Arrays .stream(text.split("\\s+")) .filter(word::equals) .count();