Write a program using Java or C# that counts the frequencies of each word in a t
ID: 656498 • Letter: W
Question
Write a program using Java or C# that counts the frequencies of each word in a text, and output each word with its count and line numbers where it appears. We define a word as a contiguous sequence of non-white-space characters. (hint: split()) Note: different capitalizations of the same character sequence should be considered same word, e.g. Python and python, I and i. The input will be several lines with the empty line terminating the text (using text file for input is optional). Only alphabet characters and white spaces will be present in the input. The output is formatted as follows:
Sample Input
Python is a cool language but Java
is also cool since it is purely object oriented language
Sample Output
1 python 1
3 is 1 2
1 a 1
1 but 1
1 cool 1 2
1 even 2
1 object 2
1 oriented 2
1 it 2
1 language 1 2
1 Java 1
1 purely 2
1 since 2
I'm trying to solve this using java and I can't figure out how to get the line number of each different appearance, it just prints the number of times it appears before the word. Here is what I have:
public class Test {
public static void main(String[] args)
{
String text = "Python is a cool language but Java " +
"is also cool since it is purely object oriented language ";
String[] keys = text.split(" ");
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
int line2 = text.indexOf(' ');
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println(count +" "+ key);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
}
Explanation / Answer
import java.util.HashMap; import java.util.Scanner; import java.util.Set; public class Countcharacters { /** * @param args */ static HashMap countcharact=new HashMap(); static HashMap linenumbertrack=new HashMap(); static int count=1; static void countwords(String line){ //System.out.println(line); String[] input=line.split("\s"); int j=0; String linenumber=""; for(int i=0;iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.