-1

beginner at java was asked in an interview here i have to count the occurrence of each word in a given sentence. for eg( "chair is equal to chair but not equal to table." Output : chair :2, is :1, equal :2, to :2, but :1, not :1, table :1 ) I have written some part of the code and tried using for loop but i failed....

public static void main(String[] args) 
{
            int counter = 0;
   String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work."; 

   String[] b =a.split(" "); //stored in array and splitted

 for(int i=0;i<b.length;i++)
 { 
     counter=0;
     for(int j<b.length;j>0;j--)
     {      
         if(b[i] = b[j])
          //


     }
 }       
}

}

mann
  • 11
  • 1
  • 1
  • 2
  • Hey mann, you should read up on *[ask]* and also check out *[Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question)* – domsson Mar 31 '17 at 22:16
  • Also, what kind of interview is that? – domsson Mar 31 '17 at 22:22
  • Also read: [How do I compare strings in Java?](http://stackoverflow.com/q/513832/5221149) – Andreas Mar 31 '17 at 22:39

6 Answers6

1

Use a hashmap to count frequency of objects

import java.util.HashMap;
import java.util.Map.Entry;

public class Funly {
    public static void main(String[] args) {
        int counter = 0;
        String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

        String[] b = a.split(" "); // stored in array and splitted
        HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
        for (int i = 0; i < b.length; i++) {
            String key = b[i];
            int freq = freqMap.getOrDefault(key, 0);
            freqMap.put(key, ++freq);
        }
        for (Entry<String, Integer> result : freqMap.entrySet()) {
            System.out.println(result.getKey() + " " + result.getValue());
        }
    }
}
Robert I
  • 1,509
  • 2
  • 11
  • 18
1

Quite easy since Java8:

 public static Map<String, Long> countOccurrences(String sentence) {
    return Arrays.stream(sentence.split(" "))
            .collect(Collectors.groupingBy(
                            Function.identity(), Collectors.counting()
                    )
            );
}

I would also remove non literal symbols, and convert to lowecase before running:

String tmp = sentence.replaceAll("[^A-Za-z\\s]", "");

So your final main method for interview will be:

ppublic static void main(String[] args) {
    String sentence = "To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
    String tmp = sentence.replaceAll("[^A-Za-z\\s]", "").toLowerCase();
    System.out.println(
            countOccurrences(tmp)
    );
}

Output is:

{diligent=1, a=1, work=1, myself=1, opportunity=1, challenging=1, an=2, associate=1, innovative=1, that=1, with=1, provide=1, and=2, provides=1, organization=1, to=2, job=1}

Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21
0

A simple (but not very efficient) way would be to add all the elements to a set, which doesn't allow duplicates. See How to efficiently remove duplicates from an array without using Set. Then iterate through the set and count the number of occurrences in your array, printing out the answer after each set element you check.

Community
  • 1
  • 1
Slepz
  • 460
  • 3
  • 18
0

There are several solutions to this and I'm not going to provide you with any of them. However, I'm going to give you a rough outline of one possible solution:

You could use a Map, for example a HashMap, where you use the words as keys and the number of their occurrence as values. Then, all you need to do is to split the input string on spaces and iterate over the resulting array. For each word, you check if it already exists in the map. If so you increase the value by one, otherwise you add the word to the map and set the value to 1. After that, you can iterate over the map to create the desired output.

domsson
  • 4,553
  • 2
  • 22
  • 40
0

You need to use Map data structure which stores data in key-value pairs.

You can use the HashMap (implementation of Map) to store each word as key and their occurance as the value inside the Map as shown in the below code with inline comments:

String[] b =a.split(" "); //split the array
Map<String, Integer> map = new HashMap<>();//create a Map object
Integer counter=null;//initalize counter
for(int i=0;i<b.length;i++) { //loop the whole array
     counter=map.get(b[i]);//get element from map
     if(map.get(b[i]) == null) { //check if it already exists
          map.put(b[i], 1);//not exist, add with counter as 1
     } else {
          counter++;//if already eists, increment the counter & put to Map
           map.put(b[i], counter);
     }
}  
Vasu
  • 21,832
  • 11
  • 51
  • 67
0

Using simple For loops

public static void main(String[] args) {

    String input = "Table is this Table";
    String[] arr1 = input.split(" ");
    int count = 0;

    for (int i = 0; i < arr1.length; i++) {
        count = 0;

        for (int j = 0; j < arr1.length; j++) {
            String temp = arr1[j];
            String temp1 = arr1[i];

            if (j < i && temp.contentEquals(temp1)) {
                break;

            }
            if (temp.contentEquals(temp1)) {
                count = count + 1;

            }

            if (j == arr1.length - 1) {
                System.out.println(">>" + arr1[i] + "<< is present >>" + count + "<< number of times");

            }

        }

    }

}
shashi
  • 1