-1

Below is the code:

import java.util.*;
import java.io.*;
public class MyClass {
    public static void main(String args[]) 
    {
        Scanner scn = new Scanner(System.in);
        String str = scn.nextLine();
        String[] arr = str.split(" ");
        for(int i =0; i<arr.length; i++)
        {
            int count = 0;
            for(int j =0; j<arr.length; j++)
            {
                if(arr[i] == arr[j])
                {
                    count++;
                }
            }
            System.out.print(count + " ");
        }

    }
}

How can I count each value of a repeated word in a string?

Shane Bishop
  • 3,905
  • 4
  • 17
  • 47
anuj
  • 11

1 Answers1

1

You are doing comparison with == while you should do comparison of strings with .equals() or with Objects.equal() method. The == does memory comparison in string pool and not content comparison.

I have changed your program:

class MyClass {
  public static void main(String args[]) {
    Set<String> visited = new HashSet<>();
    Scanner scn = new Scanner(System.in);
    String str = scn.nextLine();
    String[] arr = str.split(" ");
    for (int loop = 0; loop < arr.length; loop++) {
      int count = 0;
      for (int j = loop; j < arr.length; j++) {
        if (arr[loop].equals(arr[j])) {
          count++;
        }
      }
      if (!visited.contains(arr[loop])) {
        System.out.print(arr[loop] + " occured : " + count + " times.\n");
        visited.add(arr[loop]);
      }
    }
  }
}

The program outputs better and handles duplication as well now

OUTPUT:

hi hi hi
hi occured : 3 times.
hi how are you? hi
hi occured : 2 times.
how occured : 1 times.
are occured : 1 times.
you? occured : 1 times.
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31