PDA

Click to See Complete Forum and Search --> : # of occurrences of a word.{resolved}


System_Error
Oct 30th, 2004, 03:46 PM
I've been trying to write a program that reads text from a file and then counts the number of times a certain word occures(such as "if"). I got the part were it reads the text from file but not sure how to count the number of times a word appears. Anyone know of a method on how to do this??

System_Error
Oct 31st, 2004, 02:13 PM
I got it now.


import java.io.*;
import java.util.*;

public class ReadingFromFile
{
public void findString() throws IOException
{
String filename;
String stringToSearchFor;
System.out.println("Please enter the name of the file to search");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
filename = br.readLine();
System.out.println("Please enter the string to search for");
stringToSearchFor = br.readLine();
try {

BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
int count = 0;
while((str = in.readLine()) != null)
{
StringTokenizer parser = new StringTokenizer(str);
while (parser.hasMoreTokens())
{
String s = parser.nextToken();
if (s.equals(stringToSearchFor))
{
count++;
}
else {}

}
}
System.out.println("The word " + stringToSearchFor + " appeared " + count + " times");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}




import java.io.*;

public class TestReadingFromFile
{
public static void main(String[] args) throws IOException
{
ReadingFromFile rff = new ReadingFromFile();
rff.findString();
}
}

vbNeo
Nov 2nd, 2004, 10:12 AM
I wouldn't recommend throwing IOException as you do, it really is bad coding style - handle it right away and get rid of it =).

System_Error
Nov 2nd, 2004, 03:24 PM
Originally posted by vbNeo
I wouldn't recommend throwing IOException as you do, it really is bad coding style - handle it right away and get rid of it =).

Hey guiness the code requires that you throw an IO Exception. Not throwing an IO Exception would be bad coding in this situation. IT'S THERE BECAUSE IT SIGNALS THAT AN I/O EXCEPTION OF SOME SORT HAS OCCURED.---Not doing so would be "bad coding style" as you put it.

Why don't you try not throwing the exception like you suggested and seeing if the code works.

CornedBee
Nov 2nd, 2004, 04:37 PM
vbNeo's suggestion was reasonably polite, well-meant and sensible. Your reply sounded rather rude. Well, sounded to me, anyway.

vbNeo is right that your exception handling is flaky. You catch some exceptions and let others through. And main should never throw, anyway. It's the last stand of your program. Catch every exception there, even if you do nothing but print a stack trace and quit.

But findString - why do you catch all exceptions from the block that handles the file, but let exceptions from reading the console pass? That is inconsistent and doesn't make sense. Your function returns as if nothing bad had happened if the file can't be read - and freaks out when the console can't be read.

What you should do is to wrap only the creation of the FileReader in its own try-catch block and handle the IOException there, so you can give the user a meaningful message like "file not found" or "permission denied". All other exceptions get out of findString because it can't handle them. That's the idea behind exception handling.

Dillinger4
Nov 2nd, 2004, 06:14 PM
Yes i definitely agree with CornedBee that the main method or main thread of execution(whichever you want to call it) should never throw exceptions. It is prefectly legal but any exceptions that are thrown from the main will only be handled by the runtime.

Dillinger4
Nov 2nd, 2004, 06:16 PM
Also it wouldn't hurt to throw in some finally{}'s to close any open resources. Like files, sockets, db connections ect.... :)

System_Error
Nov 2nd, 2004, 06:28 PM
I'm sorry if my response was somewhat rude, but I misunderstood what he was meaning until CornedBee clarified it and when he did, I realized that vbNeo was right(sorry:blush: ).

I understand why that I shouldn't throw exceptions at the findString() method, but why should the main method never throw exceptions?...I see tutorials on sun.java that do it all the time when dealing with IO..
Now could someone fix the program the way it should correctly be written?

Dillinger4
Nov 2nd, 2004, 06:52 PM
When an exception occurs you usually want to either catch it then do somthing like log the error or whatever or if the method does not want to deal with the error declare that the method can throw the exception which will bubble up to it's caller. If the findString method chooses to not catch the exception and just throw it then it must be handled where it is being invoked in your case because the findString() method is invoked from the main thread. If findString() was invoked from a different context other than the main thread then that context could either deal with the exception in a try catch block or delcare that it throws the exception again. Some where along the line the exception must be delt with or it will bubble up right to the runtime.

CornedBee
Nov 3rd, 2004, 02:26 AM
import java.io.*;
import java.util.*;

public class ReadingFromFile
{
public void findString() throws IOException
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Please enter the name of the file to search");
String filename = br.readLine();
System.out.println("Please enter the string to search for");
String stringToSearchFor = br.readLine();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filename));
} catch(IOException e) {
// This exception is expected and can be handled immediately.
// All others are unexpected and thus can't be handled, let
// the caller deal with them.
System.err.println("Couldn't open file '" + filename + "':\n\t" + e);
return;
}
String str;
int count = 0;
while((str = in.readLine()) != null) {
StringTokenizer parser = new StringTokenizer(str);
while (parser.hasMoreTokens()) {
String s = parser.nextToken();
if(s.equals(stringToSearchFor)) {
count++;
}
}
}
System.out.println("The word " + stringToSearchFor + " appeared " + count + " times");
}
}
}
Mind you, even better would be to make findString just take a Reader and return the token count and handle the UI somewhere else.