₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,277 members, 8,421,134 topics. Date: Friday, 05 June 2026 at 08:16 PM

Toggle theme

Problem with tracking word frequency[Java] - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingProblem with tracking word frequency[Java] (2979 Views)

1 2 Reply (Go Down)

Problem with tracking word frequency[Java] by mashnino(op): 6:50pm On Dec 28, 2012
I have been battling with this code for days now i can't seem to get it to work the way it is suppose to...

I already have it working but not the way it suppose to. The code is suppose to read a text file..

then count how many times each word appears in the text file..

Then an ASSOCIATION CLASS object, which takes the "word" and it's "frequency(the numba of times it appears)"

as an arguement i.e KEY AND VALUE. The pair is put in a "CONTAINER CLASS".

I kind of pulled true but my problem now is; the words are repeated and the frequency has gone out of hand

i don't even understand how the frequency works sef..

Files

MAIN CLASS:

package ics202.lab02;
import java.io.*;
import java.util.Scanner;
import ics202.*;

public class TestAssociation{

public static void main(String[] args)throws IOException{
MySearchableContainer container = new MySearchableContainer();
String fileName = "C:\\Users\\Umar Mash\\Desktop\\input.txt";
File name = new File(fileName);
Scanner reader = new Scanner(name);
reader.useDelimiter("[ :;,.?\"\n\r\t!-]+"wink;
Association association;
int counter = 0;
String word="";
//Iterator it = container.iterator();

while(reader.hasNext()){

word = reader.next();
// to be completed by students
int wordChecker = word.compareTo(reader.next());
if(wordChecker == 0) {
counter++;
}
container.insert(new Association(word,counter));
}

// Display the container contents using a PrintingVisitor object
// to be completed by students

container.accept(new PrintingVisitor());
System.out.println();


}
}
and this is the text file

Dhahran
ics202 is a very interesting course.
It teaches us data structures and some new interesting concepts.
Design patterns extends the idea of code reusability another step up.
ics 202 ics202 ics202 course course.
Dhahran and Dhahran and Dhahran Dhahran Dhahran Dhahran
NB:the words in the text file cannot be more than 100

I am a 300level computer science student and this is part of our lab work assignment
the topic we are actually treating is data structures
Re: Problem with tracking word frequency[Java] by Javanian: 8:47pm On Dec 28, 2012
First of all, Next time please don't direct the problem to me, i have a life outside Nairaland you know grin and i may not always be available to help.
Next time you want to read from a text file use the classes in the java.io package and not the scanner class.
I wasn't able to re write the entire code beacause i didn't see all your classes, but we can still work out something.


while(reader.hasNext()){

word = reader.next();
// to be completed by students
int wordChecker = word.compareTo(reader.next());
if(wordChecker == 0) {
counter++;
}
container.insert(new Association(word,counter));
}
if i am right this is where you have problem with your code. Now i wrote a new class that handles this problem so it would be easy to re use my code in yours


import java.util.Scanner;

import java.util.Scanner;

public class TestAssociation
{
public static void main(String[] args)
{
//Now i didnt read from a test file but i'm assuming this are
//all the words in your text file, so what you should do is read the entire
//text file to a string

String value = "aaa bbb ccc ddd aaa ccc aaa aaa";

//basically, what this does is split all the words in the string above
//into a an array using a white space as a delimiter, so you can add more
//patterns to the delimiter as the case may be

String[] values = value.split("\\s"wink;

//Now i wrote a checkNum method as you can see below that checks the number
//of times each word you pass into it as parameter
//so for example your text file has the String "Java is really really great"
//the word "Java" will be value[0], so you pass in value[0] and value(which is the array itself)
//as parameter

System.out.println(checkNum(values[2], values));

//so in your code you can now do something like
//container.insert(new Association(word,checkNum(values[2], values));
//in your iterator

}
public static int checkNum(String value, String[] values)
{
int counter = 0;
for(int i =0; i <values.length; i++)
{
if(value.equals(values[i]))
{
counter++;
}
}
return counter;
}

}
Re: Problem with tracking word frequency[Java] by mashnino(op): 8:54pm On Dec 28, 2012
I am so sorry for that...

Lemme check it out...

would let you know if it works
Re: Problem with tracking word frequency[Java] by mashnino(op): 9:21pm On Dec 28, 2012
The problem with BufferedReader is that, it doesn't have a method that checks if there's a next word.

and i used the "readLine()" to convert the text file to a string, i don't know if i am suppose to do so
Re: Problem with tracking word frequency[Java] by Javanian: 9:29pm On Dec 28, 2012
^^^

There are a lot of ways you can work around that code, but if you are to follow my implementation, you have to read the text file into a String...
Re: Problem with tracking word frequency[Java] by mashnino(op): 9:33pm On Dec 28, 2012
to just make the whole thing easier...

just show me a piece of code i can use to check the number of times

a word appears in a text file...

using Scanner...i will connect the whole code together myself..

cos dats just the part that is giving me problem...
Re: Problem with tracking word frequency[Java] by Javanian: 9:44pm On Dec 28, 2012
But thats what i gave you now, all you need to do is read the text file to String, that isn't difficult now, or is that what you need?
Re: Problem with tracking word frequency[Java] by mashnino(op): 9:53pm On Dec 28, 2012
jez did that...

the value of "value" doesn't change...

unlike Scanner class, bufferedReader don't have the "hasNext()" and "next()" Method..

that's where my problem is from now...
Re: Problem with tracking word frequency[Java] by Javanian: 9:55pm On Dec 28, 2012
Why don't you just stick to the Scanner class to avoid complicating issues...
Re: Problem with tracking word frequency[Java] by mashnino(op): 9:58pm On Dec 28, 2012
ok...lemme try it around with the scanner class den...
Re: Problem with tracking word frequency[Java] by segsalerty(m): 11:00pm On Dec 28, 2012
Just passing by wink........... this sounds like an ACM trouble? Wat sch abeg? cheesy :DPost d whole problem and test sample input and output grin so we go fit brainstorm together better than reading ur code
Re: Problem with tracking word frequency[Java] by csharpjava(m): 12:05am On Dec 29, 2012
If you don't mind me intruding as this is meant for Javanian, then I think what you need is a Java map, see example below from mkyong.com/java/how-to-loop-a-map-in-java which you can modify.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMap {

public static void main(String[] args) {

// initial a Map
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Jan"wink;
map.put("2", "Feb"wink;
map.put("3", "Mar"wink;
map.put("4", "Apr"wink;
map.put("5", "May"wink;
map.put("6", "Jun"wink;

System.out.println("Example 1..."wink;
// Map -> Set -> Iterator -> Map.Entry -> troublesome
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey()
+ ",value is :" + mapEntry.getValue());
}

System.out.println("Example 2..."wink;
// more elegant way
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}

System.out.println("Example 3..."wink;
// weired way, but work anyway
for (Object key : map.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ map.get(key));
}

}

}
Re: Problem with tracking word frequency[Java] by Fayimora(m): 12:58am On Dec 29, 2012
As already stated, please post your problems without directing it at anyone. You just end up putting folks off. I've changed the topic wink
Re: Problem with tracking word frequency[Java] by mashnino(op): 2:45am On Dec 29, 2012
fank you fayimora...i ve alwais wanted to be here alwais but it seemed like there was no java person...

so sorry about that
Re: Problem with tracking word frequency[Java] by mashnino(op): 2:47am On Dec 29, 2012
csharpjava: If you don't mind me intruding as this is meant for Javanian, then I think what you need is a Java map, see example below from mkyong.com/java/how-to-loop-a-map-in-java which you can modify.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMap {

public static void main(String[] args) {

// initial a Map
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Jan"wink;
map.put("2", "Feb"wink;
map.put("3", "Mar"wink;
map.put("4", "Apr"wink;
map.put("5", "May"wink;
map.put("6", "Jun"wink;

System.out.println("Example 1..."wink;
// Map -> Set -> Iterator -> Map.Entry -> troublesome
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey()
+ ",value is :" + mapEntry.getValue());
}

System.out.println("Example 2..."wink;
// more elegant way
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}

System.out.println("Example 3..."wink;
// weired way, but work anyway
for (Object key : map.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ map.get(key));
}

}

}
This MAP class is almost the same thing as the Association class in which i am working with..
Re: Problem with tracking word frequency[Java] by mashnino(op): 2:50am On Dec 29, 2012
This is the initial question

Complete the program TestAssociation.java to associate each word in a text file with
its number of occurrence (i.e., with its frequency), using the word as the key and the
number of occurrence as the value. Use an instance of MySearchableContainer to
store the Association objects. After processing all the words, print your container
using the PrintingVisitor of the ics202 package.
and defaultly the TEST ASSOCIATION class looks like this

package ics202.lab02;
import java.io.*;
import java.util.Scanner;
import ics202.*;

public class TestAssociation{

public static void main(String[] args)throws IOException{
MySearchableContainer container = new MySearchableContainer();
Scanner reader = new Scanner(new File("input.txt"wink);
reader.useDelimiter("[ :;,.?\"\n\r\t!-]+"wink;
Association association;

while(reader.hasNext()){
String word = reader.next();

// to be completed by students








}


// Display the container contents using a PrintingVisitor object
// to be completed by students




}
}
and mine is above in which i haven't completed...got stuck in the same position as i explained above...
Re: Problem with tracking word frequency[Java] by Nobody:
Re: Problem with tracking word frequency[Java] by segsalerty(m): 11:41am On Dec 29, 2012
mashnino: fank you fayimora...i ve alwais wanted to be here alwais but it seemed like there was no java person...

so sorry about that
Are u kidding me? I contributed, got no response, smh.......... thats really hw to learn! Kudos..... cheesy
Re: Problem with tracking word frequency[Java] by segsalerty(m): 11:55am On Dec 29, 2012
Anywayz, i changed my mind.... wat ur teacher wants to see is hw u will implement a Map.

Store words as Map<String, WordClass>,
After reading/scanning each word in d text file, use map function that checks if key exist in d map. If yes..... get the WordClass value and increament its counter/occurence property. Else. Put into d map a new key(the new word) and new instance of (wordclass). With these, u will fulfil d task given.
Here is a simple skelenton of ur WordClass cass

Properties
String word;
int counter or occurence;
Constructor
WordClass(String w){
Word=w;
Occurence=0;
}

Increment(){
Occurence++;
}// call dis when such word exist in map

Other fuctioms u need are ur getters.



Hope dis helps solve ur assignment
Re: Problem with tracking word frequency[Java] by mashnino(op): 1:18pm On Dec 29, 2012
segsalerty: Are u kidding me? I contributed, got no response, smh.......... thats really hw to learn! Kudos..... cheesy
lol..sorry man..ahn ahn

don't take it personal now...
Re: Problem with tracking word frequency[Java] by mashnino(op): 1:26pm On Dec 29, 2012
Okay guys.. seriously speaking i am lost within the codes you guys are dropping.

let me post the output of my own code maybe you guys can finally fish out where i am not getting it right

{ Dhahran , 0 }
{ is , 0 }
{ very , 0 }
{ course , 0 }
{ teaches , 0 }
{ data , 0 }
{ and , 0 }
{ new , 0 }
{ concepts , 0 }
{ patterns , 0 }
{ the , 0 }
{ of , 0 }
{ reusability , 0 }
{ step , 0 }
{ ics , 0 }
{ ics202 , 1 }
{ course , 2 }
{ Dhahran , 2 }
{ Dhahran , 2 }
{ Dhahran , 3 }
{ Dhahran , 4 }
and my code is up there, don't wanna post it again so that it won't fill up the whole place..

and this is the text file that must not have more than hundred words

Dhahran
ics202 is a very interesting course.
It teaches us data structures and some new interesting concepts.
Design patterns extends the idea of code reusability another step up.
ics 202 ics202 ics202 course course.
Dhahran and Dhahran and Dhahran Dhahran Dhahran Dhahran
To just make the whole problem short...

If you guys can just help me with a method that counts the number of times each word in a text file appears in that same text file..

assuming you are using a scanner class to read the words from the text file..

NB: I can't deviate from the skeleton that was given, that's why i can't use the MAP class..

I think that's why the assignment is this complicated.

If you also notice the code skips some words from the text file. I don't know why that is that..
Re: Problem with tracking word frequency[Java] by segsalerty(m): 2:17pm On Dec 29, 2012
Zip wats needed abt d assignment and send to my email. Segsalerty@yahoo.com will look into when i get on system.
mashnino: lol..sorry man..ahn ahn

don't take it personal now...
Lolz, i gats kpara for u nau! Wondering where u got ur fact frm......

Elm, less i forget.... i go like to toast javanian if toastable, make i knw her first coz all i see on dis section is javanian here,javanian there...... winks kiss
Re: Problem with tracking word frequency[Java] by mashnino(op): 2:20pm On Dec 29, 2012
^^ d chick bad gan..
Re: Problem with tracking word frequency[Java] by segsalerty(m): 2:24pm On Dec 29, 2012
mashnino: ^^ d chick bad gan..
Seen her before? Abeg give me her facebook name make i peep! Send am too to my email smiley wink
Re: Problem with tracking word frequency[Java] by mashnino(op): 3:59pm On Dec 29, 2012
Just sent you the file...^^^
Re: Problem with tracking word frequency[Java] by segsalerty(m): 4:49pm On Dec 29, 2012
public class TestAssociation{

public static void main(String[] args)throws IOException{
MySearchableContainer container = new MySearchableContainer();
String fileName = new File(""wink.getAbsolutePath()+"\\input.txt";
FileReader name = new FileReader(fileName);
Scanner reader = new Scanner(name);
reader.useDelimiter("[ :;,.?\"\n\r\t!-]+"wink;
Association association;
int counter = 1;
String word="";
Map<String, Integer> tempMemory = new HashMap<String, Integer>();
//Iterator it = container.iterator();

while(reader.hasNext()){

word = reader.next();
// to be completed by students

if(!container.isMember(new Association(word))){
container.insert(new Association(word,counter));
tempMemory.put(word, counter);
}
else{
container.withdraw(new Association(word));
int prevCount = tempMemory.get(word);
int newCount = prevCount+1;
container.insert(new Association(word,newCount));
tempMemory.remove(word);
tempMemory.put(word, newCount);

}
}
// boolean wordChecker = word.equals(reader.next());
// if(wordChecker == true) {
// counter++;
// }
// container.insert(new Association(word,counter));
// }

// Display the container contents using a PrintingVisitor object
// to be completed by students

container.accept(new PrintingVisitor());
System.out.println();
}
}
sorry, i had to rush this, clean up ur code, nepa is bringing and taking light.... bt this concept works fine thou there are flaws in d design of the classwork libraries (some functions are missing thats suppose to be there in "MySearchableContainer" to make it more efficient) well, it works fine this way, ask me anything u dnt understand, will respond via mobile.


NOTE : [s]output is nt 100% right, bt its smth u can fix wink[/s] Light is back, output is 100% correct now, so, just recopy paste and rerun
Re: Problem with tracking word frequency[Java] by mashnino(op): 5:37pm On Dec 29, 2012
Shit shit shit!!!!!!!

I have mixed feelings here...

i am sad because i culdn't do it

i am happy because i have learnt some new stuffs...

I am gonna sit down and study the stuffs...

THANKS to everybody that contributed..i really appreciate..

THANK YOU GUYS..

"jumping around my room"
Re: Problem with tracking word frequency[Java] by mashnino(op): 5:46pm On Dec 29, 2012
Please do me all of us here a favor..

Xplain where my mistake is from so that anybody that comes accross this topic would benefit...

Jez for the house...

Fanx so much
Re: Problem with tracking word frequency[Java] by segsalerty(m): 5:46pm On Dec 29, 2012
mashnino: Shit shit shit!!!!!!!

I have mixed feelings here...

i am sad because i culdn't do it

i am happy because i have learnt some new stuffs...

I am gonna sit down and study the stuffs...

THANKS to everybody that contributed..i really appreciate..

THANK YOU GUYS..

"jumping around my room"
grin Good for u Boss .... wish our institutions can give these tasks in Nigeria. so bad and poor of our school sad cry .
NB: i still get interest ontop this javanian o, why is she ignoring my interest nwhuhhuh haba, i will go on Nairaland strike again if she no respond o! kiss
Re: Problem with tracking word frequency[Java] by Nobody:
Re: Problem with tracking word frequency[Java] by segsalerty(m): 6:34pm On Dec 29, 2012
mashnino: Please do me all of us here a favor..

Xplain where my mistake is from so that anybody that comes accross this topic would benefit...

Jez for the house...

Fanx so much
Do that urself sir wink
Re: Problem with tracking word frequency[Java] by mashnino(op): 6:56pm On Dec 29, 2012
Ok... Will xplain... Laptop dead.. No light on my mobile phone...
1 2 Reply

How To Create A Shipping Tracking On Website.?I Have A Problem With Raise Event In C#234

Where Can I Learn Programming In Lagos?Microsoft Launches Silverlight: An Alternative To FlashYii2 Rest API Question