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

Dani AI

Generated

asked for a program that counts how many times a given term appears in a text file (example: "PRINTER" -> "printer = 2"). The posted snippet has a couple of immediate problems: a compile-time mismatch (declares char inputxt but uses nextLine()), a typo (intputxt), and a logic issue — using indexOf counts lines that contain the query substring instead of exact token occurrences and does not handle case or punctuation. 's request for error details is warranted: the code will produce compile errors and, once fixed, may still give wrong results for inputs like printer, or Printer.

A simple, robust approach:

  • Read the file line by line.
  • Turn each token into a normalized key (trim + lower-case; optionally strip punctuation).
  • Maintain a Map<String,Integer> of frequencies.
  • Answer queries by looking up the normalized key in the map (or scan the file per query if memory is a concern).

Example implementation (Java 8+):

import java.nio.file.*;
import java.io.*;
import java.util.*;

public class WordCounter {
  public static void main(String[] args) throws IOException {
    Path path = (args.length > 0) ? Paths.get(args[0]) : Paths.get("task2.txt");
    Map<String,Integer> counts = new HashMap<>();
    try (BufferedReader br = Files.newBufferedReader(path)) {
      String line;
      while ((line = br.readLine()) != null) {
        String[] tokens = line.trim().split("[^A-Za-z0-9]+");
        for (String t : tokens) {
          if (t.isEmpty()) continue;
          String key = t.toLowerCase(Locale.ROOT);
          counts.merge(key, 1, Integer::sum);
        }
      }
    }
    try (Scanner sc = new Scanner(System.in)) {
      System.out.print("Enter term (-1 to exit): ");
      while (sc.hasNextLine()) {
        String q = sc.nextLine().trim();
        if ("-1".equals(q)) break;
        String key = q.toLowerCase(Locale.ROOT);
        System.out.printf("%s = %d%n", q, counts.getOrDefault(key, 0));
        System.out.print("Enter term (-1 to exit): ");
      }
    }
  }
}

Notes and cautions: use Locale.ROOT when lower-casing to avoid locale surprises; choose the split regex to match expected input (one-word-per-line vs. sentences). For extremely large files and a single query, it is cheaper to scan the file once counting matches rather than building a full map.

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.