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); } } } public static int countThe(Scanner words, String word) { int count = 0; while (words.hasNext()) { if (words.next().equalsIgnoreCase(word)) { count++; } } return count; } public static int totalwords(Scanner words) { int x = 0; while (words.hasNext()) { x++; } return x; } }
Alright, so what I'm trying to do is import a .txt file, use it as a scanner, and then have it search for the number of times the input word is used inside of the .txt file. That part works. I also want it to count the total number of words in the file. That part doesn't work and I can't seem to figure out why, especially as that should be the easier part of this. I'm very new to java, please help me!
EDIT: It returns "x", so it is reaching that part of the code, but it's like it is already at the end of the text file so there isn't a chance for it to go through the while method. Is there a way I can reset the scanner to start from the beginning of the file again? Or am I completely off about that?