Stupid word count problem

Idea of the code is to count the number of times "hat" is typed into the console. When the program sees "PERIOD" it is supposed to end and print out how many times it saw "hat".
here is what I have:
import java.util.Scanner;
public class wordCount {
     public static Scanner keyboard;
     static public void main(String[] arg)
          int numHats = 0;
          keyboard = new Scanner(System.in);
          while(!(keyboard.next().matches("PERIOD")))
               if(keyboard.next().matches("hat")) numHats++;
          System.out.println("Occurances= "+numHats);
          System.exit(0);
}and yet with this input:
super hat awesome
cow pig hat
hat hat pig
hat cow sweet hat hat
PERIODI get this output:
Occurances= 5I know that the problem is with the .next function, that it is skipping some of the hats but I dont know how to fix it...any help? I know it cant be that difficult of a problem

The problem with your code is that each time you invoke keyboard.next(), you jump to the next token. If the input is
hat hat hat
PERIOD
then first hat will be checked if it matches "PERIOD", it does not so the while loop continues. You invoke again keyboard.next() and your token is the second hat. As it matches "hat" your count is now =1.
Again keyboard.next() is invoked in while loop, the current token is the third hat. It does not match PERIOD so we go into the loop and here again keyboard.next() is invoked so our token is PERIOD. It does not match with hat so no incrementing in count. As you can see the app didnt stop because the code is problematic.
use while(keyboard.hasNext()) which iterates you thru every token and then take each token with keyboard.next(). Later see if it matches with "hat" or "period". I'm sure that'll help.

Similar Messages

  • Problem with getting word count in TLF text

    Hi,
    I want to get the word count from my TLF text, but the problem is that I am not being able to handle th case for space.
    I am using the findNextWordBoundary property of ParagraphElement as shown below:
    private function countWords( para : ParagraphElement ) : void
                var wordBoundary:int = 0;
                var prevBoundary:int = 0;
                while ( wordBoundary != para.findNextWordBoundary( wordBoundary ) )
                   // If the value is greater than 1, then it's a word, otherwise it's a space.
                    if ( para.findNextWordBoundary( wordBoundary ) - wordBoundary > 1)
                        wordCount += 1;                   
                    prevBoundary = wordBoundary;
                    wordBoundary = para.findNextWordBoundary( wordBoundary );                   
                    // If the value is greater than 1, then it's a word, otherwise it's a space.
                    if ( wordBoundary - prevBoundary > 1 )
                        var s:String = para.getText().substring( prevBoundary, wordBoundary );
                        lenTotal += s.length;
    Now I have 2 issues here:
    If my string is for eg: Hi, I am writing in "TLF". And I want to get its word count then
    1) Suppose I take the case of the string Hi,  . Then para.getText().substring( prevBoundary, wordBoundary ) gives the text as Hi i.e without the comma. Same case for the string "TLF forums" , It treats each " as a single word and not the whole "TLF" as a single word. Why doesn't it compute till spaces, that should be the ideal case. So until we don't give a space it should count the whole thing as a word.
    2) So now the problem is I have applied a condition   if ( wordBoundary - prevBoundary > 1 ) to check if it is a space i.e. if the diff is <= 1 it is a Space. But if I use this I miss out on single words. Like for eg if I have "Hi, This is a string" ,then 'a' is ignored too.
    Now I could have added a check here along with the space check that the string between prevBoundary and wordBoundary is " "(i.e a space), Then also it is a problem as then the single words like a,&,I will be ignored.
    So, now I am stuck with this issue and need some help from you guys.
    Thanks

    findNextWordBoundary is not going to serve your purpose.  I'd propose doing something like this:
    // didn't test this but something like this - whitespace matches any set of 1 or more white space characters
    static const whiteSpaceRegExp:RegExp = /[u0020|u000A|u000D]*/
    public static function countWords( para : ParagraphElement ) : void
         return para.getText().split(whiteSpaceRegExp).length;
    A good list of everything considered whitespace extracted from the unicode space can be found here:
    http://sourceforge.net/adobe/tlf/svn/449/tree/trunk/textLayout/src/flashx/textLayout/utils /CharacterUtil.as
    In function createWhiteSpaceObject
    Hope that helps,
    Richard

  • Problem with Korean Word Counting

    After upgrading to Yosemite 10.10.3, Korean word counting in Pages got mesed up. Before the upgrade, there was no problem. But now Pages counts every single letter I typed as a "word." As a writer who should be sensitive to the number of words I type, this is very annoying. Is there anyone who experiences the same problem? is there any fix?

    See
    Korean word count

  • 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

  • Why is the word count function inaccurate in tables?

    Why, when using tables in pages the word count function gives a total that is double the amount of words in the table? This has been a problem with Pages for sometime now. Additionally, is there a quick way of highlighting all the words in the table to give a word count total, similar to highlighting a paragraph, sentence or just a few words?

    Pages v5.2.2 (and probably 5.5) will total all the words in the body of a document (including those in a table) accurately in my experience. Since the Pages v5 family does not permit non-contiguous text selection, your only other way to count just words within the table is from the Statistics component of the free WordService Services package. Just select the table, and then from the Services menu, choose Statistics. The word count matches the table contents.
    Unfortunately, the AppleScript dictionary  for the Pages v5 family excludes any means to address words or characters within cells. The fact that Pages is counting words in the table, is due to native programming, and not AppleScript.

  • After installing lion and updating to pages 4.1 cannot view my document content after I open the document.  Shows how many pages I have and how many words in word count, but no words...

    after installing lion and updating to pages 4.1 cannot view my document content after I open the document.  Shows how many pages I have and how many words in word count, but no words...

    Same problem. Tried reinstalling Pages. Didn't help. The behavior is like I am typing with a white font on a white background, but I am not.

  • Array words count

    Hi guys
    This code is giving me this output
    The New York Times is an American daily newspaper founded and continuously published in New York City since September 18 1851 It has won 112 Pulitzer Prizes more than any other news organization 0
    I need to read and split the array (I believe that part works)
    I also need to count the words and display it like this
    The(1)  New(2) York(2) Times(1) is (1) ...etc
    I am   System.out.print(token + " "  ) ; then I need to count the words and display the number in front
    Thank you
    package test4;
    import java.util.StringTokenizer;
    * @author rechever
    public class Test4 {
         * @param args the command line arguments
        public static void main (String[] args) {
           System.out.println("Displaying a paragraph: ”): ");
                String sentence1 = "The New York Times is an American daily newspaper, founded and continuously published "
                        + "in New York City since September 18, 1851. It has won 112 Pulitzer Prizes, more than any other news organization";
        //        String sentence1  = scanner.nextLine();
          /* regular expression   */
          sentence1 = sentence1.replaceAll("\\,"," ");
          sentence1 = sentence1.replaceAll("\\."," ");
          sentence1 = sentence1.replaceAll("\\;"," ");
                StringTokenizer stt = new StringTokenizer(sentence1," ");
              // int countWords = 1;  
                while
                    (stt.hasMoreTokens()){
                    String token = stt.nextToken();
                   System.out.print(token + " "  ) ;
                 // String  value = sentence1;
                 //  String value = token;
              //  insertNode(value);
              //  insertNode(value);
                for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
                } // end of Main  

    Believe I try before I ask, if you see the code I was able to split the array, I am having problems with the counts and displaying the results in front of the words..
    as you can see I initiated the loop, I just can not get it to work...
    for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
                } // end of Main 
    I need to able to split the array
    StringTokenizer stt = new StringTokenizer(sentence1," ");
              // int countWords = 1;  
                while
                    (stt.hasMoreTokens()){
                    String token = stt.nextToken();
                   System.out.print(token + " "  ) ;
    then after the array split I need to counts the words,
    this 
    for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
    is not doing the trick..
    I am in the business of learning, I am not looking for a free ride...I google it, I look in books
    This code is doing it but I have to call a method to insert the array in a Binary tree
    something like tree.insertNode (value)
    being value the data stoom the split array....
    Now if you want to give some ideas (a link, documentation anything of how to call a method from  a class that is using maps...that will be great
    I though that doing it in a simple array was easy... again, I just learning
    Thank you
    import java.io.PrintStream;
    import java.util.*;
    public class WordTypeCount
       public static void main( String[] args )
          // create HashMap to store String keys and Integer values
          Map< String, Integer > myMap = new HashMap< String, Integer >();
          createMap( myMap ); // create map based on user input
          displayMap( myMap ); // display map content
       } // end main
       // create map from user input
       private static void createMap( Map< String, Integer > map )
          Scanner scanner = new Scanner( System.in ); // create scanner
          System.out.println( "Please Enter the sentence from the the from Edgar Allen Poe’s “Fall of the House of Usher”):" ); // prompt for user input
          String input = scanner.nextLine();
          // tokenize the input
          String[] tokens = input.split( " ");
          // processing input text
          for ( String token : tokens )
             String word = token.toString(); 
                     ///toLowerCase(); // get lowercase word
             // if the map contains the word
             if ( map.containsKey( word ) ) // is word in map
                int count = map.get( word ); // get current count
                map.put( word, count + 1 ); // increment count
             } // end if
             else
                map.put( word, 1 ); // add new word with a count of 1 to map
          } // end for
       } // end method createMap
       // display map content
       private static void displayMap( Map< String, Integer > map )
          Set< String > keys = map.keySet(); // get keys
          // sort keys
          TreeSet< String > sortedKeys = new TreeSet<  >( keys );
          System.out.println( "\nMap contains:\nKey\t\tValue");
          // generate output for each key in map
          for ( String key : sortedKeys )
          // System.out.printf( "%-10s%10s\n", key, map.get( key ) );
          System.out.printf( "%-5s%-5s", key,map.get( key ) );
         // System.out.printf("\nsize: %d\nisEmpty: %b\n", key, map.get( key ) );
          System.out.printf(
             "\nsize: %d\nisEmpty: %b\n", map.size(), map.isEmpty() );
       } // end method displayMap
    } // end class WordTypeCount
    Thank you

  • I'm writing a word-count program

    I'm sure this question has come up often but I've searched the web and haven't found a straight-forward answer for my problem. I need to write out a program that simply counts the number of words in a file of text.
    This has to be done in two different ways:
    1)Using a string object where I input each line.
    2)Assuming the string class doesn't exist, and to input the data one character at a time.
    Now, I know you won't do the work for me, and I haven't been able to figure out any code to put in yet. I just could use a push in the right direction with this. I haven't been able to find any good examples of this type of programming.

    1)Using a string object where I input each line.You could [url http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html]read the text file line by line.
    For each line you could [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)]split it using [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#sum]the regular expression character for whitespace (zero or more times).
    The number elements of the returned array is is the word count for each line.
    2)Assuming the string class doesn't exist, and to input the data one character at a time.You could still read the text file in the same way as previously but instead of using the readLine() method
    you should use the [url http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#read()]read() method.
    Each time the returned byte is either ' ', '\t', '\f', '\r' or '\n' (and that the previous byte is not) you could increment the word counter.
    Regards

  • Tools Scripts Word Count is broken; can I fix it?

    RH HTML; 8.0.2.208
    The script at "Tools > Scripts > Word Count" says "Bad Argument GetTokenManager" and fails.
    It broke while I had 8.0.1, or maybe while I had 8.0.0.
    Can I fix this?

    HI,
    if the script is working for a dummy project, it means the script is working fine, and there is some issue when we run this script in your project.
    Please open script pod and right click on the word count.jsx file and select edit option. this will open the word count script in Extendscript editor (or notepad).
    Search for the following line in the script file var tknmgr = RoboHelp.getTokenManager (filepath);
    and add the following statement before this line.  msg(filepath);
    so the new code looks like
    msg(filepath);
    var tknmgr = RoboHelp.getTokenManager (filepath);
    Now save this file and again run the script file from RoboHelp 8 by right click and run.
    this will show the messages in the output view, as to which topic it is trying to open using the token manager and we can get to know where the script is breaking.
    it will print the file path of the topic which is causing the problem, Please see if you can open that topic from project manager in your Project or not.
    Do let me know the log in the output view, after you have modified the script file and run it again.
    -Praful

  • 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)  

  • Word Count Method?

    Hey all. I am having a bit of an issue. I need to write a program to read a file and count how many words are in the file. So far I have the basis for the while loop to read a line from the file, but I can't seem to figure out how to code the loop to count the words. Java doesn't have a word count method does it? I have looked, but have been unable to find anything of the sort.
    I don't want you do do this for me, I just need some helpful hint/tips. Anything you can provide is appreciated. Thanks!

    I am now having this problem. Here is a code segment:
    void count(String newFileName) throws IOException
              fileName = newFileName;
              FileRead file = new FileRead(fileName);
              wordCount = 0;
              StringTokenizer st = new StringTokenizer(fileName);
              while (file.getLine() != null)
                 while ( st.hasMoreTokens() )
                    st.nextToken();
                    wordCount++;
         }I think it should be changed to StringTokenizer st = new StringTokenizer(file) but when I do so, I get the error "The constructor StringTokenizer(FileRead) is undefined". I assume this is because file is an object not a String variable. the current code has a problem because it only returns 1. Any ideas?
    Edited by: zcrane on Nov 1, 2007 3:40 PM

  • 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

  • Pages 08' Word Count?

    Is there a word count for Pages 08? If so, how do I see it or view it?

    PeterBreis0807 wrote:
    But Yvan I had to teach you how to do that.
    You had to teach me that quotes are required for Preview under 10.5 because I don't use 10.5 !
    In fact I don't use Preview because I prefer Adobe Reader which displays my docs a better way.
    here Preview under 10.5
    here Adobe Reader (10.4 and/or 10.5)
    More to the point is that if the Word Count function is in a logical location, why are so many unable to find it without resorting to searches of the manual?
    Because most of them doesn't search seriously.
    But, even it the location was odd, it's not normal that they ask here before searching in the Help AND in the PDF User Guide.
    The forum is not a catch all questions recipient.
    The Help and terms of use clearly urges them to search in the delivered resources.
    These resources are:
    (1) the menus themselves
    (2) the Inspectors themselves
    (3) the Help
    (4) the PDF User Guide which is delivered with every copy of iWork, on disk or in downloaded versions
    (5) last not least, in the existing threads.
    For my own use, I searched in the Help and in the PDF because I was surprised to read users claiming that they didn't found the info.
    Doing that, I discovered that what _I got in the Edit menu_ is also available in an Inspector in which I had never searched as I was already able to get the tool in the menu.
    When I searched in the Help I found nothing useful.
    When I searched in the PDF, as I am running 10.4, Preview and Adobe Reader gave the response instantaneously.
    You wrote here that under 10.5, Preview behaves differently.
    I checked and in my response I wrote that quotes may be required.
    Last not least, searching in the existing threads give also the response immediately.
    So, from my point of view, if we continue to read the question here it's only because many users think _"why would I make the effort to search by myself when there will be some one which will give the response on the forum"_ . In other words, lazyness is becoming the rule.
    Yvan KOENIG (from FRANCE mercredi 24 septembre 2008 17:28:05)

  • Is there a way to exclude title, heading and bibliography text from the word count in pages?

    I've just got the newest version of pages.
    The word count includes everything, from titles to endnotes - including the numbers in my sub-headings.
    I used to use open office where you could select a style i.e. 'body tex't, and get a word count that didn't include every single word in a document.
    Is there a way of doing something similar, or reseting the word count to only 'body text' so I know exactly how long my essays are?
    Thanks.

    Unfortunately, no version of Pages has this fine-grained control over document components and their word count, so the answer is no, regarding user changeable settings.
    Programmatically, I just told AppleScript to count the words of body text in a currently opened Pages v5.2 document. The count matched the Pages word count for the document. So, no solution there either.

  • Does anyone know why the word count in Word for Mac changes so drastically? In one document it goes up and down by several hundred at a time when I have done nothing but scroll through the document.

    I am new to the wonderful world of Mac and all of my documents were created in MS Word on my old laptop. I noticed that the word counts were slightly different when I opened the documents in Word for Mac, but then I noticed that they changed drastically. For intance, I opened a document today and after the initial period where the word count shifts, it seemed to settle on 13,171. I left the document for a while to work on some other things and when I came back the word count had changed to 11,677. I didn't do anything to the document. Word counts are important to me since I need at least 60,000 for my PhD Dissertation. Which word count should I trust?

    Since Word is a Microsoft product, you should probably post your question on the Microsoft Mac forums:
    http://answers.microsoft.com/en-us/mac

Maybe you are looking for

  • Can I show a webform success or error message on a PageID redircted page?

    I have the web app edit form redirecting to the members main area. Is it possible to add a success or error feedback box in this area? Does BC pass any module data that can accessed? Thanks in advance. * I have feeling it is something to do with the

  • Skype 7.1 crashing with APPCRASH

    the Skype 7.0 related discussion[This discussion was split from the Skype 7.0 related discussion as it's now about Skype 7.1] I have the same problem. and the link for previous build is not correct.

  • HT5312 I dont have a Rescue email address and how i can reset Apple ID security questions

    I dont have a Rescue email address and how i can reset Apple ID security questions Regards

  • Tftpd and TCP wrappers

    I'm unable to wrap the tftpd service on our system. The server is not denying tftp (get) requests from arbitrary Internet hosts, in spite of: /etc/hosts.deny: in.tftpd: ALL TCP wrappers is enabled for tftpd: # inetadm -l svc:/network/tftp/udp6:defaul

  • Fonts Needed

    I am in need of Edwardian Script ITC, CalistoMT, and CalisMT Bold.  Looking for a reputable online souce to get those fonts from.  I don't want to download something that will utimately harm my PC. Using CS6. Thanks!