Coding Help Hashmap Java? I need a code ( IN JAVA) that uses a hashmap... that c
ID: 664116 • Letter: C
Question
Coding Help Hashmap Java?
I need a code ( IN JAVA)
that uses a hashmap... that counts the characters and in one method gives the characters alphabetically.
The other gives it in order of frequency( most frequent to least)
I can share what i have but i don't think its right
example:
Then, after the function call freqDistribution("essay.txt", "freq.txt"), a file called freq.txt should contain the following
b 1 c 1 h 1 n 2 o 4 r 1 w 4
After the function call ordered freqDistribution("essay.txt", "ordfreq.txt"), a file called ordfreq.txt should contain the following: o 4 w 4 n 2 b 1 c 1 h 1
Explanation / Answer
working code. compiled on ideone
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String str = "abc abc abc 123";
Hashtable numbers = new Hashtable();
int size = str.length();
for(int i = 0 ; i< size ; i++)
{
char curr = str.charAt(i);
if(numbers.contains(curr) == false)
{
numbers.put(curr, 1);
}
else
{
numbers.put(curr, ((int)numbers.get(curr)) + 1);
}
}
Enumeration names = numbers.keys();
char c;
while(names.hasMoreElements()) {
c = (char) names.nextElement();
System.out.println(c + ": " +
numbers.get(c));
}
}
}
https://ideone.com/hnkh27