Word count application

Hi am attempting a previous exam question and would appreciate some advice:
I have been given a class that has been partly implemented. The class called Document
that determines how many words are in the document, and how many certain specified
words are in the document. That is, there is a TotalWordCount and a GetWordCount method
which determines these.
The second class is a test class for the Document class (see below).
My questions are, what would be appropriate code for the constructor? I am assuming I only need
to pass the name of the file (which the constructor already does?) What would a suitable means to count the number of words? I am unsure how to count individual specified words. (I have implemented a simply word count class that only counts ALL words).
Lastly, does my Document tester class appear to be correct? (in context to the Document class).
Any help/advice sincerely appreciated!
Regards,
Benjamin.
import java.io.*;
import java.util.*;
public class Document extends File{
     private int totalWordCount = 0;
     public Document (String filename){
          super(filename);
     //constructor code goes here
     public int getWordCount () {
     return totalWordCount;
     public int getWordCount (String[] words){
          return countWords(this.getName(), words);
     private int countWords (String filename, String[] words) {
          String line, token;
          StringTokenizer tokenizer;
          int wordCount = 0;
          //create the procedure for counting the words;
     return(wordCount);
import java.io.*;
import java.util.*;
public class DocumentTest{
     public static void main(String[] args){
          String filename = "myfile.txt";
          Document myDoc;
          myDoc = new Document();
          system.out.println(myDoc.getWordCount);
          system.out.println(myDoc.getWordCount("a");
          system.out.println(myDoc.getWordCount("and");
          system.out.println(myDoc.getWordCount("the");
          system.out.println(filename);
          //Create a new document
          //print out a total word count
          //print out the number of times the words "a", "and" or "the"
          //appear in the file
          //Print out the Documents name using myDoc
          try{
          FileReader fr = new FileReader(filename);
          BufferedReader inFile = new BufferedReader(filename);
}

Yeah its a bit messy, there was nothing wrong with 'extends File' and the call to super(string) per se, its just a bit untidy as, even though it takes the String path/name in the constructor, it makes the code less readable IMO.
You might be better off with something more along the lines of this - its a suggestion and neither is it complete;-import java.io.*;
import java.util.*;
class MyDocumentCounter{
   private int totalWordCount = 0;
   File file;
   String fileName;
   String fileString;
   int wordsInFile;
   public MyDocumentCounter (String fileName){
      this.file = new File(fileName);
      this.fileName = fileName;
      this.fileString = readNewFile(file);
      this.wordsInFile = setWordCount(fileString)
      setWordCount(fileString);
   private String readNewFile(File file){
      StringBuffer sb = new StringBuffer();
      try{
         BufferedReader buf = new BufferedReader(new FileReader(file));
         String text;
         while ( (text = buf.readLine()) != null) sb.append(text);
         buf.close();
      }catch(IOException ioe) { ioe.getMessage(); }
      return sb.toString();
   public int setWordCount(String fileString) {
      StringTokenizer tkn = new StringTokenizer(" \n",fileString);
      return tkn.countTokens();
   public int getWordCount(){
      return wordsInFile;
   public int countThisWord(String word) {
     return counter;
}I'll leave you to figure out the countThisWord() method. And java.io.File has a very useful method;-
myFileName.exists() which returns a boolean

Similar Messages

  • How do you get word count to print at the end of a document in Pages?

    How do you get word count to print at the end of a document in Pages?

    Pages v5 does not provide a user assignable word count variable. With some AppleScript, and a paste operation from the clipboard, you can have locale punctuated word count in this format: 7,803 — anywhere in your document. The following AppleScript works with Pages '09 v4.3 through Pages v5.5.2 on Yosemite.
    I would suggest that you copy paste the following AppleScript into your [Apple] Script Editor and save it (suggestion) wordcnt.applescript. Then, follow this with an option+Save As… and this time set the File format to Script Bundle, or Application with hidden extension — saved to your Desktop. Provided you have a Pages document open, you are then a double-click from the ability to paste your current word count into Pages.
    Note: If you have Pages word count display enabled, it will automatically count your pasted value as another word which initially may deceive on true word count at the time the script was run.
    AppleScript
    --- copy below this line ---
    property locale : "en_US.UTF-8" -- In Terminal, use the locale command to see yours
    if not ApplicationIsRunning("Pages") then
         display dialog "Pages must be running to use this utility."
         return quit
    end if
    tell application "Pages"
        tell body text of front document
            set wordCnt to count words
            -- Don't want punctuated numbers? Remove the single quote from printf format
            set the clipboard to (do shell script "export LC_ALL=" & locale & "; printf \"%'d\" " & wordCnt)
        end tell
    end tell
    on ApplicationIsRunning(appName)
         tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
         return appNameIsRunning
    end ApplicationIsRunning

  • Can you do a Word Count in Pages?

    I am working on College essays and applications and a lot of the essays they require you to write can only be so many words. Is there a way to do a word count on Pages? On my PC, Microsoft Word 07 automatically has the word count in the bottom of the window.
    Please help!

    In the inspector there is an automatic word count in the document section. All you need to do is select the info column and it should be there!
    John

  • Indesign CS6 Total Document Word Count... No?

    I left the following comment on a Youtube tutorial explaining how to execute a word count query for an Indesign document ASSUMING your article layout uses a single box of text:
    What if an article uses a creative layout with multiple text-boxes? Are you supposed to get out your pocket calculator and add them up one-by-one?
    I work for a magazine that publishes short, submission-style testimonials bridged together with staff-generated narrative copy; some of our articles use six or more discreet text-boxes. You REALLY MEAN TO TELL ME that there is NO WAY to yield a TOTAL DOCUMENT WORD COUNT using what is SUPPOSED TO BE the MOST ADVANCED page layout application ON EARTH??
    Pardon my exasperation in the above comment, but....Seriously?  
    I need someone knowledgeable to please look me in the eyes and tell me, "This is true", before I am going to be able to let myself believe it.
    Thank you.
    - Exasperated Journalist Slag

    Yes, there are ways, just not what you expected.
    One approach to counting words in multiple text frames in InDesign is to thread them together. To maintain the pieces of text in their assigned threaded text frames, you can create a paragraph style that starts in the next frame, and assign it to the first paragraph in each text frame. Or, you can break the threads when the count is stable.
    If the text frames need to adjust their size to the amount of their content, search Google for terms like "indesign auto resize text frame" without quotes for details.
    There was a recent discussion about auto-resizing text frames that mentioned the free AutoFit InDesign plug-in, from typefi.com. Search Google for terms like "indesign typefi autofit" for details.
    Search Google for terms like "threading and unthreading InDesign text frames" without quotes, for details.
    Search Google for terms like "indesign start paragraph in next frame" without quotes, for details.
    You can file a formal feature improvement request here: Wishform.
    HTH
    Regards,
    Peter
    Peter Gold
    KnowHow ProServices
    evanexempt wrote:
    I left the following comment on a Youtube tutorial explaining how to execute a word count query for an Indesign document ASSUMING your article layout uses a single box of text:
    What if an article uses a creative layout with multiple text-boxes? Are you supposed to get out your pocket calculator and add them up one-by-one?
    I work for a magazine that publishes short, submission-style testimonials bridged together with staff-generated narrative copy; some of our articles use six or more discreet text-boxes. You REALLY MEAN TO TELL ME that there is NO WAY to yield a TOTAL DOCUMENT WORD COUNT using what is SUPPOSED TO BE the MOST ADVANCED page layout application ON EARTH??
    Pardon my exasperation in the above comment, but....Seriously?  
    I need someone knowledgeable to please look me in the eyes and tell me, "This is true", before I am going to be able to let myself believe it.
    Thank you.
    - Exasperated Journalist Slag

  • Word count and my ActionPerformed

    I am having a little trouble with my program and was wondering if anyone could spot the mistake... I am trying to make a simple application that will count the number of words in a text field via click of a button and display the results.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
    // added JTextPane, JScrollPane, JPanel JTextField, and JButton
        public static void main(String[] args)
         // layout
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
             if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         } // end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
         JTextPane jtPane = new JTextPane();
         JScrollPane jsPane = new JScrollPane(jtPane);
         JPanel south = new JPanel();
         JTextField wordCount = new JTextField(20);
         JButton jbtCount = new JButton("Count Words");
        public static void main(String[] args)
              int width = 700;
              int height = 300;
               WordCount f = new WordCount();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.setSize(width, height);
             f.setTitle("Word Counter");
             f.setLocation(200, 200);
             f.setVisible(true);
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
                  // *** process Button actions
            if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         }// end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

  • How do I get a word count in Pages 5.5.2?

    I have a 21.5" iMac, bought December, 2014. I have Yosemite 10.10.2 installed and I am using Pages 5.5.2.
    How do I get a Word Count in Pages 5.5.2?

    View menu > Show Word Count.
    A floating panel will appear at the bottom of your document. Pass your mouse over the right-side of this floating panel and you will see up/down arrows. Click. Choose Word count from the list of available counts. The floating panel now displays word count, until you change it again. You can also move this floating panel with a command+click+drag, in case you want it below your footer content.
    You might want to download the free WordService service solution from the OS X App Store. I provides you with many additional features (e.g. Sort Ascending, Document Statistics, etc.) The act of downloading this application will install, but not activate several services. You activate what you want in:
    System Preferences > Keyboard > Shortcuts > Services : WordService:servicename.
    The WordService application will be in your LaunchPad (on your left Dock). Run it and choose Help. This will launch the Preview PDF viewer and a document showing all the Services available, and their description. Services in OS X act on selected document content. If you want more detail on the number of words, characters, and spaces in a selected paragraph, you would use Pages > Services > WordService:Statistics.

  • How can I find the total word count in my entire Indesign CS3 document?

    I have a book that consists of 10 different files and many many different text boxes. I need to find out what the total word count is for the entire book. Is there a simple way to do this, or do I have to copy and paste all the text from InD into a word file to get the number? Your help is much appreciated.

    This AppleScript will get the total word counts of a folder of ID files—it shouldn't be too hard to convert to JavaScript if you are not using OSX:
    tell application "Finder"
    activate
    set myFolder to choose folder with prompt "Select the folder containing the files to count"
    set myFiles to every file of folder myFolder whose file type is "IDd5"
    end tell
    tell application "Adobe InDesign CS3"
    set wordcounts to {}
    set total to 0
    repeat with j from 1 to (number of items in myFiles)
    open item j of myFiles
    tell active document
    tell every story
    set wordcounts to wordcounts & (count every word)
    end tell
    set totalstories to count every item of wordcounts
    repeat with i from 1 to totalstories
    set total to total + (item i of wordcounts)
    end repeat
    close
    end tell
    end repeat
    display dialog "The documents in the selected folder have a total of " & totalstories & " stories, and " & total & " words"
    end tell
    ========================================
    If you just want the active document's count it would be:
    tell application "Adobe InDesign CS3"
    tell active document
    set wordcounts to {}
    tell every story
    set wordcounts to wordcounts & (count every word)
    end tell
    set total to 0
    set totalstories to count every item of wordcounts
    repeat with i from 1 to totalstories
    set total to total + (item i of wordcounts)
    end repeat
    display dialog "Total words in all " & totalstories & " stories: " & total
    end tell
    end tell

  • Is it possible to sort by word count

    I have a list of titles and wish to arrange them by the number of words in each title, any suggestions gratefully received

    Hi FF,
    Word processing applications usually define a 'word' as a group of characters followed by a space (or a return).
    I haven't foud a way to directly count the number of spaces in a string of text, but Numbers does support FIND() which can determine the position of a specific character's first appearance in a string or after a specified position in a string.
    That's the method used in the coloured cells of the table below.
    C2: =IFERROR(FIND(" ",$B,1+MAX($B2:B2)),"")
    Fill right for as many cells as there are words in the 'longest' title.
    Fill down to the end of the table.
    A count of the cells containing numbers in the row (not including the cell in A, which must be a Header column) will give the number of spaces in the title. Add 1 for the number of words in the title.
    A2: =IF(LEN(B)>0,COUNTIF(2:2,">0")+1,"")
    Fill down to the last row in the table.
    Sort on column A to arrange the titles by length in words.
    Note the results in rows 5 and 6.
    Row 5 contains the title of Paul Zindel's 1964 play as he wrote it. Man-in-the-Moon is considered as a single word in the count.
    Row 6 contains the same title with the hyphens replaced by spaces. Man in the Moon now counts as 4 words.
    Rows 7 and 8:
    George Orwell's title is read as a number. As it's greater than 0, the number is included in the count. 1 is added to account for there being no space after the 'last word' in the title to give a count of 2. (Result is the same when the title is entered as '1984 (the leading ' tells Numbers, and other spreadsheets, to format the cell as text), of when the cell's format is set to Text using the Inspector.)
    In row 8, 1984 is enclosed in quotation marks, and is now treated as text (with a numerical value of zero).
    As noted, the columns doing the calculations may be hidden.
    Regards,
    Barry

  • How can I get a word count in iCloud Pages Beta?

    Apparently there is no way to get a document word count in iCloud Pages Beta.  Has anyone figured out a work around for this?

    View menu > Show Word Count.
    A floating panel will appear at the bottom of your document. Pass your mouse over the right-side of this floating panel and you will see up/down arrows. Click. Choose Word count from the list of available counts. The floating panel now displays word count, until you change it again. You can also move this floating panel with a command+click+drag, in case you want it below your footer content.
    You might want to download the free WordService service solution from the OS X App Store. I provides you with many additional features (e.g. Sort Ascending, Document Statistics, etc.) The act of downloading this application will install, but not activate several services. You activate what you want in:
    System Preferences > Keyboard > Shortcuts > Services : WordService:servicename.
    The WordService application will be in your LaunchPad (on your left Dock). Run it and choose Help. This will launch the Preview PDF viewer and a document showing all the Services available, and their description. Services in OS X act on selected document content. If you want more detail on the number of words, characters, and spaces in a selected paragraph, you would use Pages > Services > WordService:Statistics.

  • Cs3 word count slow

    the word count in my indesign cs3 takes several minutes to calculate a 120 000 word document. i never had this issue with cs2. (apart from changing from cs2 to cs3, i've upgraded from tiger to leopard, and upped the ram on my imac g5 from 768mb to 2gb).
    any ideas?
    william

    There doesn't seem to be a problem getting the word count via a script. The Applescript below returns the total word count. I tested it on a doc with 28000 words and it returned the count instantly on my MacPro.
    tell application "Adobe InDesign CS3"
    tell active document
    set wordcounts to {}
    tell every story
    set wordcounts to wordcounts & (count every word)
    end tell
    set total to 0
    set totalstories to count every item of wordcounts
    repeat with i from 1 to totalstories
    set total to total + (item i of wordcounts)
    end repeat
    display dialog "Total words in all " & totalstories & " stories: " & total
    end tell
    end tell

  • Continuous Word Count

    Hi, is there a way to make a script that will always show the word count in TextEdit? If so, how do I make it? Can the script show word count while typing? Apple should consider adding word count to TextEdit.
    Thanks,
    Sarah

    Another stunning answer from Bang.
    There's no inherent way of doing this. The closest you can get is an idle script that continually (or, at least, periodically, polls the front document, counts the words and displays it in some manner.
    The main issue you'll have is how to display it in a non-intrusive way (e.g. you don't want to pop up a dialog box every few seconds). Here's one idea that kind of hacks it together, by putting the word count into a background window:
    tell application "TextEdit"
      global WordCountDoc
      make new document -- make a new doc
      set WordCountDoc to id of window 1 -- remember it
      set WordCountWindow to window 1 -- find its window
      set bounds of WordCountWindow to {20, 100, 200, 200} -- and reposition it
      set ActualDocument to make new document -- here's the real doc we're going to count
    end tell
    on idle
      global WordCountDoc
      tell application "TextEdit"
        set wordCount to 0 -- assume an empty document
        try
          set wordCount to (count (words of (text of document of front window)))
        end try
        set text of (document of window id WordCountDoc) to (wordCount as text)
      end tell
      return 10 -- check again in 10 seconds
    end idle
    Save it as a 'stay open' script and launch it when you're ready.
    It's certainly not as elegant as a 'true' word count built into the application (e.g. it polls every n seconds rather than counting as you type), but it gives you a start.

  • How do you find the word count on MacBook, please?

    How do you find the word count on MacBook, please?

    If you are trying to find word count in a Microsoft Word 2011 documemt, for instance, open the document and go to the Tools menu, selecting Word Count. In Apple's Pages application, open the document and look at the bottom of the page, near the left it will say "X Words" where X is the number.
    Best of luck.

  • Approximate word count

    Publishers don't really care how many actual words there are in a document, they care about an approximate number of words. Average number of letters per line divided by 6 multiplied by the average number of lines times the number of pages. Are there any add-ons or built in features that can do that automatically?
    It's no problem doing it manually, but if I have to restrict something to so many words it would be nice to know where I am at with a few clicks.

    Hi -
    Word count is in Document Inspector (first icon on the left.) Open it, click on info.
    It gives you everything from word count to character count.
    For selected areas: I copy a selection and paste it into a blank Pages document, then check word count in Inspector. That is best if you are as lazy as I am and can't be bothered with downloading additional software. Another concern: Pages are and absolute memory guzzler - computer slows down if you open too many applications.
    Hope this helps,
    Sashura, http://i-work-in-pages.blogspot.com
    iMac, iBook   Mac OS X (10.4)  

  • TextEdit Word Count?

    Hi folks, I'm relatively new to Apple. (New enough to not know the proper forum for this question, though). Can I do a word count in TextEdit? If so, how? Any help is greatly appreciated.

    Here is the applescript to tell you the word count:
    tell application "TextEdit"
    set WordCount to the number of words in the the front document
    display dialog "The wordcount is: " & WordCount
    end tell
    What you need to do to install this is this:
    Run the program called "Scripteditor", which you can find somewhere in the programs directory - there is no point in my trying to tell you where as my system is set up in Foreignspeak. You'll have to run a search, which thankfully is very easy!
    To make a new script press apple-n, then copy and paste the text I gave above into the window that appears. Then run the script and it will tell you how many words there are in your current TextEdit file.
    There is probably a neater way of running the script than opening ScriptEditor, but given that I have been playing with this stuff for only a very short period of time I don't know about it yet.
    Best Wishes, Max
    p.s. My favourite script of the moment, which speaks whatever I type:
    set toSay to "I would like a cup of tea."
    repeat
    set toSay to the text returned of (display dialog "Max doeth speak:" default answer toSay)
    say toSay
    end repeat
    (childish, I know!)
      Mac OS X (10.4.3)  

  • How do I see my word count on Pages 5.1?

    I just downloaded Pages 5.1 on my Mac, but I'm beginning to not like the changes. For example, where can I find my word count without pasting the entire body of the document into an outside source?
    Thanks for your help!

    You are aware that Apple has removed over 100 features form Pages 5 and added a long list of bugs, including problems opening files?
    Pages '09 should still be in your Applications/iWork folder.
    Stick with that until Apple fixes Pages 5 or an alternative arises.
    Peter

Maybe you are looking for