Word Counter Help

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: May 2006
Posts: 1
Reputation: Zxenobia0 is an unknown quantity at this point 
Solved Threads: 0
Zxenobia0 Zxenobia0 is offline Offline
Newbie Poster

Word Counter Help

 
0
  #1
May 4th, 2006
I need help working on my Java project. Any amount is welcome.
The project needs to prompt the user for a file input (txt), file output, and five words to search through the input file. Each input needs to be equipped with try and catch code to prevent crashing. The program then counts each instance of the word in the input file and outputs the results in the designated output file entered by the user.

I'm currently just working on the file input portion and trying to prompt the user to "Enter input file" even after the first attempt was caught by the catch FileNotFound Exception.

Here's my current code.

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class WordCounter{


public static void readFile (){
String word = "";
System.out.println("Enter input file:");
Scanner scanner = new Scanner (System.in);
File file = new File(scanner.next());
String line = "";

try{
scanner = new Scanner (file);
}
catch(FileNotFoundException exception){
System.out.println(exception);
System.out.println("Not a valid file");
System.out.println("Enter input file:");

}


while (scanner.hasNextLine()){
line = scanner.nextLine ();
}

System.exit(0);
scanner.close();
}
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 786
Reputation: Phaelax is on a distinguished road 
Solved Threads: 39
Phaelax Phaelax is offline Offline
Master Poster

Re: Word Counter Help

 
0
  #2
May 4th, 2006
For getting a file, you could take a look at JFileChooser.
  1. String input = "a line from the file";
  2. String word = "key word to search for";
  3. int occurrences = 0;
  4. int index = 0;
  5. while ((index = input.indexOf(word,index)) > -1 && index < input.length())
  6. {
  7. occurrences++;
  8. index += word.length();
  9. }
  10. System.out.println(occurrences);
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC