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 = "";

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


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


For getting a file, you could take a look at JFileChooser.

String input = "a line from the file";
String word = "key word to search for";
int occurrences = 0;
int index = 0;
while ((index = input.indexOf(word,index)) > -1 && index < input.length())
     index += word.length();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.