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

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class TextAnalysis {

    public static void main(String[] args) throws Exception {

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        JFileChooser chooser = 
                new JFileChooser("c:/users/zachary/demo");

        int outcome = chooser.showOpenDialog(null);

        if (outcome == JFileChooser.APPROVE_OPTION) {

            File f = chooser.getSelectedFile();
            Scanner words = new Scanner(f);


            String word = JOptionPane.showInputDialog("Enter word");
            if (word != null) {

                int count = countThe(words, word);
                JOptionPane.showMessageDialog(null, "Count: " + count);
                int allwords = totalwords(words);
                JOptionPane.showMessageDialog(null,  "Total Words: " + allwords);
                int length = total(words);
                JOptionPane.showMessageDialog(null, "Total Letters:" + length);

            }

        }

    }

    public static int countThe(Scanner g, String word) {
        int count = 0;

        while (g.hasNext()) {
            if (g.next().equalsIgnoreCase(word)) {
                count++;
            }
        }
        return count;
    }

    public static int totalwords(Scanner in) {
        int allwords = 0;


        while (in.hasNext()) {
            allwords++;
        }

        return allwords;
    }

    public static int total(Scanner in) {

        int z = 0;
        int length = 0;

        while (in.hasNext()) {

            String test = (in.next());
            z = test.length();
            length = z + length;

            }

        return length;
    }

}

Alright, so here is my code. What I'm trying to do is be able to select a .txt file and then count the number of times the input word is found. This part works. However, I would also like to count the number of words in the total document as well as the total number of characters in each word. I can't get this part to work and I'm not sure why. I have it working if I input the scanner from a different method, but I can't get it to work with using the same scanner that I'm already using. Is there a way I can reset the scanner for each method it gets to or something? Please help, thanks!

its because scanner class reach to end when counting the letter. It will return 0 for other two.
1) You can solve this by making a string. and pass that string to scanner
2) make a custom class which has three variable count, total count and length. and make function accordingly and check all of three variable in a function.

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.