Question:
How to make count consistent across numbers?

Problem:

I am doing an assignment and need to build a word frequency calculator. The first integer is the total number of words in the input.


Ex: If the input is:


5 hey Hi Mark hi mark Expected output is:


hey 1 Hi 2 Mark 2 hi 2 mark 2


My Output is: hey 1 Hi 1 Mark 1 hi 2 mark 2


import java.util.Scanner;


public class LabProgram {


   public static int getWordFrequency(String[] f, int size, String c){

      int count = 0;

      for (int j = 0; j < f.length; j++) {

          if (f[j] != null && f[j].equalsIgnoreCase(c)) {

              count++;

          }

      }

      return count;

   }


   public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in);

      int size = scnr.nextInt();

      String c;

      int i;

      String [] f = new String[size];

      int [] v = new int[size];

      for (i = 0; i < size; i++) {

          f[i] = scnr.next();

          c = f[i];

          v[i] = getWordFrequency(f, size, c);

      }

      for(i = 0; i < size; i++){

         System.out.println(f[i]+ " " + v[i]);

          }

       }

    }


Solution:

Here is an example.

Scanner in = new Scanner(System.in);

Map<String, Integer> m = new TreeMap<>();

for (int i = 0, n = in.nextInt(); i < n; i++)

    m.merge(in.next().toLowerCase(), 1, (a, b) -> ++a);


Output

5 hey Hi Mark hi mark

{hey=1, hi=2, mark=2}


The reason this is happening is because you're checking f upon each iteration.


Populate f fully, and then traverse, and invoke getWordFrequency, for each.


for (i = 0; i < size; i++) {

    f[i] = scnr.next();

}

for(i = 0; i < size; i++){

    System.out.println(f[i]+ " " + getWordFrequency(f, size, f[i]));

}


Output

5 hey Hi Mark hi mark

hey 1

Hi 2

Mark 2

hi 2

mark 2


Alternately, you can utilize a >List, and the >Collections#frequency method.

Scanner in = new Scanner(System.in);

List<String> l = new ArrayList<>();

for (int i = 0, n = in.nextInt(); i < n; i++)

    l.add(in.next().toLowerCase());

for (String s : l)

    System.out.printf("%s %s%n", Collections.frequency(l, s), s);


Output

5 hey Hi Mark hi mark

1 hey

2 hi

2 mark

2 hi

2 mark


Suggested blogs:

>Invoking Python script from scons and pass ARGLIST

>Migrate From Haruko To AWS App: 5 Simple Steps

>PHP cURL to upload video to azure blob storage

>PHP Error Solved: htaccess problem with an empty string in URL

>Plugins and Presets for Vuejs project

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide


Ritu Singh

Ritu Singh

Submit
0 Answers