Hi

I am trying to create a program in java which will scan for words within a text file. The program will scan the list containing a bunch of words in every line some words may be repeated. The program should scan the text file when I input a word that is similar to that found on the list, it should output how many similar words were found.

For example:

The list:
CPU
RAM
PRINTER
HDD
HDD
WLAN
PRINTER

If I input PRINTER, the program should say "printer = 2"


Here's what I have so far. If you could provide a coded solution, it will be much appreciated.

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

/** Demonstrate reading text from a file.**/
public class TextReader
{

  public static void main (String arg[]) {
	char inputxt;
	int linecount = 0;
	String line;
	
	
	PrintStream output = new PrintStream (System.out);
	Scanner input = new Scanner (System.in);
    // Count the number of lines in which the string occurs
	 System.out.print("Please enter a computer term (-1 to exit): ");
	 intputxt = input.nextLine();
   
	 String string_to_find = inputxt ;

    File file = null;
    // Get the file from the argument line.
    if (arg.length > 0) file = new File (arg[0]);
    if (file == null || !file.exists ()) {
      System.out.println ("Default: TextFileReadApp.java");
      file = new File ("task2.txt");
    }

    // Count the number of lines with the string of interest.
    int num_lines = 0;
    try {
      // Create a FileReader and then wrap it with BufferedReader.
      FileReader file_reader = new FileReader (file);
      BufferedReader buf_reader = new BufferedReader (file_reader);

      // Read each line of the file and look for the string of interest.
      do {
         String line = buf_reader.readLine ();
         if (line == null) break;
         if (line.indexOf(string_to_find) != -1) num_lines++;
      } while (true);
      buf_reader.close ();
    }
    catch (IOException e) {
        System.out.println ("IO exception =" + e );
    }
    System.out.printf ("Number of lines containing \"%s\"  = %3d %n",
                         string_to_find, num_lines);
  } // main

} //class TextFileReadApp

What exactly is the problem that you are facing? Are you facing compile time or runtime errors? If compile time, what are the errors you are getting? If runtime, what's the expected output, what are you getting instead?

Provide more details.

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.