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!