OK I got this code that works but you have to enter words on command line. You enter : Java Freq red red red blue orange (etc.), and it displays word and frequency.
-------------------------------------------------------------------------
//FREQ.JAVA
//---------
import java.util.*;
public class Freq {
public static void main(String args[]) {
Map<String, Integer> m =
new HashMap<String, Integer>();
// Initialize frequency table from command line
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null ? 1 : freq + 1));
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
}
-------------------------------------------------------------------------
How do I change the code so that instead of String args[] from command line it gets value from a string array within the code. I tried editing the code myself with a static string array called words but this does not work. What am I doing wrong?
---------------------------------------------------------------------------
//FREQ.Java
//---------
import java.util.*;
public class Freq {
public static void main(String [] words) {
Map<String, Integer> m =
new HashMap<String, Integer>();
// Initialize frequency table from command line
for (String a : words) {
Integer freq = m.get(a);
m.put(a, (freq == null ? 1 : freq + 1));
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
public static String words [] = {"red", "orange", "red", "blue", "yellow", "green"};
}
----------------------------------------------------------------------------