title: How to count the amount of times a word shows up in text file in Java?
body: <p>So I'm pretty new to Java and I'm working on a code that is supposed to read a <code>.txt</code> file that the user inputs and then ask the user for a word to search for within the <code>.txt</code> file. I'm having trouble figuring out how to count the amount of times the inputted word shows up in the <code>.txt</code> file.  Instead, the code I have is only counting the amount of lines the code shows up in.  Can anyone help me figure out what to do to have my program count the amount of times the word shows up instead of the amount of lines the word shows up in?  Thank you! Here's the code: </p>
  
  <pre><code>import java.io.File;
  import java.io.FileNotFoundException;
  import java.util.Scanner;
  
  public class TextSearch {
  
      public static void main(String[] args) throws FileNotFoundException {
          Scanner txt;
          File file = null;
          String Default = "/eng/home/tylorkun/workspace/09.1/src/Sample.txt";
  
          try {
              txt = new Scanner(System.in);
              System.out.print("Please enter the text file name or type  'Default' for a default file. ");
              file = new File(txt.nextLine());
  
              txt = new Scanner(file);
  
              while (txt.hasNextLine()) {
                  String line = txt.nextLine();
                  System.out.println(line);
              }
              txt.close();
          } catch (Exception ex) {
              ex.printStackTrace();
          }
  
          try {
              txt = new Scanner(file);
              Scanner in = new Scanner(System.in);
              in.nextLine();
              System.out.print("Please enter a string to search for. Please do not enter a string longer than 16 characters. ");
              String wordInput = in.nextLine();
  
              //If too long
              if (wordInput.length() &gt; 16) {
                  System.out.println("Please do not enter a string longer than 16 characters. Try again. ");
                  wordInput = in.nextLine();
              }
  
              //Search
              int count = 0;
              while (txt.hasNextLine()) //Should txt be in? 
              {
                  String line = txt.nextLine();
                  count++;
                  if (line.contains(wordInput)) //count &gt; 0
                  {
                      System.out.println("'" + wordInput + "' was found " + count + " times in this document. ");
                      break;
                  }
              //else
                  //{
                  //    System.out.println("Word was not found. ");
                  //}
              }
          } catch (FileNotFoundException e) {
              System.out.println("Word was not found. ");
          }
      } //main ends
  } //TextSearch ends
  </code></pre>