Counting words in a textfile

Hello I am trying to make a program that counts the number of words in a textfile specified below - later i will make it so you can choose the textfile. When I try to compile this I get the errors:
java:23: char cannot be dereferenced
               if(inWord && character.isWhiteSpace(character))
^
java:29: char cannot be dereferenced
               else if(!inWord && character.isLetterOrDigit(character))
Please could someone tell how to get this working - I know its something to do with the format of the data, maybe I should change it to a string or something?
cheers anyone
import java.io.*;
public class NumberOfWords
     public static void main(String[] argStrings)
            final int EOF = -1;
            int count = 0;
            boolean inWord = false;
            FileReader file = new FileReader("TestFile.txt");
            for(int i = file.read(); i != EOF; i = file.read())
               char character = (char)i;
               if(inWord && character.isWhiteSpace(character))
                 // we've come to the end of a word, so count it
                 count++;
                 inWord = false;
               else if(!inWord && character.isLetterOrDigit(character))
                 // we've just started a word or number
                 inWord = true;
            if(inWord)  // count the last word in the file
               count++;
      System.out.println(count);
}

Hello again, I am making great progress as I now have a program where you can specify the file and it does the required function. I would like to modify it to count the number of words on each line. Please could I have some tips on how to do this.
cheers
*Write an application which displays the number of words on each
*line of a text file. Assume one space between words, and no spaces
*at the start and end of the lines. Test the application with a
*suitable input file.
import java.io.*;
import java.util.Scanner;
public class NumberOfWords
     public static void main(String[] argStrings)throws Exception
            final int EOF = -1;
            int count = 0;
            boolean inWord = false;
            System.out.println("Enter file for word counting");
            Scanner scan = new Scanner(System.in);
            String inputFile = scan.nextLine();
            FileReader file = new FileReader(inputFile);
            for(int i = file.read(); i != EOF; i = file.read())
               char myChar = (char)i;
               if(inWord && Character.isWhitespace(myChar))
                 // we've come to the end of a word, so count it
                 count++;
                 inWord = false;
               else if(!inWord && Character.isLetterOrDigit(myChar))
                 // we've just started a word or number
                 inWord = true;
            if(inWord)  // count the last word in the file
               count++;
       System.out.println();
       System.out.println("Number of words: " + count);
}

Similar Messages

  • Counting words in a single cell in Numbers'09

    Hi there,
    I'm relatively new to Mac world, but I do have years of computer experience from a PC and have also had to do with Macs at the age of first eMacs . I have finally decided to switch to the brighter side of life (hopefully ;)).
    But here is my question: I need to count words in a cell in Numbers'09.
    Is there a specific function combination for achieving this? My idea was: strip excessive spaces, count the occurencies of all space character in a cell, add 1 and voila! Problem is I can not achieve it using formulas in Numbers'09. I have found some help for Excell but the formulas are a little different. And well, I would like to leave the past behind and stick to a Apple programs - if I can. I don't like the idea to install Excell on a Windows Bootcamp partion only for this purpose.
    Any help would be greatly appreciated. Thanks.
    Aleksander

    Badunit wrote:
    Yvan once had a list of all the different localizations. He may still have it.
    I'm late but, I was very busy
    The table with every localized functions names is (and will remain) available on my iDisk :
    <http://public.me.com/koenigyvan>
    Download :
    For_iWork:iWork '09:functionsNames.numbers.zip
    An easy soluce for foreign users (like me) is to duplicate Numbers.app and remove its languages resources minus English.
    Running it you will have it running in English (minus the decimal and the parameters separators, minus also date time formats and default currency).
    It would be easy to enter the formulas given in this forum.
    Once saved, we may open the doc in the 'standard' Numbers and the formulas will be automatically localized.
    Yvan KOENIG (VALLAURIS, France) mardi 2 mars 2010 18:30:45

  • How to count words in a PDF file?

    Is there any way I can count words in a PDF file without resorting to Acrobat Reader (which apparently has that feature)?
    That's a massive program, which I actually don't like.
    I need to count words in the PDF file because I write my papers with LaTeX, and they're full of my extensive comments.
    Do you know of any alternative?

    that utility IIRC cannot be found on xpdf (the official Archlinux package) anymore and its part of poppler
    edit: its pdftotext btw
    Last edited by dolby (2008-05-11 13:35:05)

  • Counting words in a textArea

    Help !!
    I am trying to count the number of words contained in a text area - Is it possible to do this ?
    I am new to Java and I'm stuck because I only know how to write programs that use FileReader to count the number of words in a file.
    Is it possible to count the number of words in a string directly - or will I have to save the string to file and then apply another program to count the number of words ?

    You inser this code in your source file (TextArea1 is the name of the TextArea, whose you want to count words)
    String texte=TextArea1.getText();
    String rt=String.valueOf((char)13) + String.valueOf((char)10);
    StringTokenizer mots=new StringTokenizer(texte," ,.:;!?\t"+rt);
    int nbremots=mots.countTokens();
    and you place at the header of the file
    import java.util.StringTokenizer;
    nbremots is the number of words The delimitors between words are noticed in the second argument of the constructor of class StringTokenizer. I have choosen the main signes of punctuation like space, coma,stop... the String rt
    symbolise return on Windows. If you work on Unix prefer this code
    String texte=TextArea1.getText();
    StringTokenizer mots=new StringTokenizer(texte," ,.:;!?\t\n");
    int nbremots=mots.countTokens();
    You can also with the class StringTokenizer read the words one by one with this type of boucle
    while (mots.hasMoreTokens())
    String mot=mots.nextToken();
    mots.nextToken();
    It is an useful class. See the API about this class StringTokenizer in the package java.util

  • Count words in each sentece in a file

    Hi all
    i want to ask how can i count words in each sentece in a file??
    ie if i have the follwoing sentece
    i ate the cake.
    today is Sundy.
    i went to school 5 day a week.
    to have the number as
    4
    3
    8
    any ideas??

    you could read the file line per line, put the line
    in a string and use StringTokenizer to split it into
    word and count them. Or you could read file char per
    char, increasing the word counter everytime you find
    a blank char, when the read char is a newline you
    save the old counter and start a new word count for
    the new line.That's an option, but a sentence is not ended by a newline. A sentence ends with a full stop/point.
    Kaj

  • Is there a method for counting words?

    Hi!
    Is there a method for counting words?
    How do I read specific data ( row, column ) out of an array?
    Thx
    Lebite

    There's could be a better way, but this is how I would do it:
            String[][] myArray = { {"Blah Blah Blah"},
                                   {"Blah Blah Blah"},
                                   {"Blah Blah Blah"} };
            int tokens = 0;
            for(int i = 0; i < myArray.length; i++)
                for(int j = 0; j < myArray.length; j++)
    StringTokenizer st = new StringTokenizer(myArray[i][j]);
    tokens += st.countTokens();
    System.out.println(tokens);

  • Count word without space in C#

    Dear sir,
    I would like to count word in sentence without space in c# but I could not solve this code.Please solve this one coding is below
                int i = 0,b=0;
                int Count2 = 1;
                for (i = 0; i < Paragraph.Length; i++)
                    if (Paragraph[i] == ' ')
                        for (b = i; b < Paragraph.Length; b++)
                            if (Paragraph[b] != ' ' && Paragraph[b] != '\t')
                                Count2++;
                                break;
                Console.WriteLine("Total Word = {0} .", Count2);

    Dear Sir,
    I want to count words without space in a Sentence but I face a problem that when I run the program space is also count with words but I want count only words Please guide . My C#  program is as under .
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Text.RegularExpressions;
    using System.IO;
    namespace Static_Method_Count_Word
        class Program
            static void Main(string[] args)
                Console.WriteLine("Please Enter Any Paragraph .");
                string Paragraph = Console.ReadLine();
                Count.Coun(Paragraph);
                Console.ReadLine();
        class Count
            public static void Coun(string Paragraph )
                int i = 0,b=0;
                int Count2 = 1;
                for (i = 0; i < Paragraph.Length; i++)
                    if (Paragraph[i] == ' ')
                        for (b = i; b < Paragraph.Length; b++)
                            if (Paragraph[b] != ' ' && Paragraph[b] != '\t')
                                Count2++;
                                break;
                Console.WriteLine("Total Word = {0} .", Count2);

  • How to count words in a text ?

    Hi all,
    can anyone show me how to count the number of words in a text.
    thank in advandce,
    Toan.

    Hi,
    Are you reading the text from a file or is it stored in a string buffer?
    The best way would be to use a StringTokenizer assuming that all your words are separated by a space ' ' you could use that as your delimiter.
    Something like..
    String text = "This is just a bunch of text stored as a string.";
    StringTokenizer words = new StringTokenizer( text, " ", false );
    int numberOfWords = words.countTokens();I hope that helps,
    .kim

  • IBooks Author seems to have stopped counting words at a bit under 20,000.  Page count is wrong too.  Anyone else seen this or know what's wrong?

    I believe I'm updated to the latest version of iBooks Author, and have crossed over 20,000 words on my book, and it seems to be stuck at 19,267 words.  My page count is up to 91 but iBooks Author says 85 (that one is easier to verify, but word count simply isn't moving at this point.  I browsed a bit but didn't find the issue reported elsewhere.  Is there perhaps an option I'm missing or something?  It seemed to be just fine, and when I got things transferred from Pages the word count was at least similar to what it was so I think it's been working.

    Fabe, thanks for asking clarifying questions. Inspector in iBooks Author tells me there are 85 pages, and the page count next to the thumbnails tells me a different number, saying the last page is 91.  That is not including front matter so, yes, there are more pages.  In fact, many more since there is a quite a bit more white space in the iBooks version.  As for word count and being able to enter more text, I really didn't notice that the word count was not changing until I had checked back several times and noticed it hadn't crossed over 20,000 words and then noticed that the number looked awfully familiar.  In my case, it certainly seems to be stuck at 19.267 words, and I don't see any other negative effects.
    Steve

  • Counting words in a text widget

    Hi,
    Is there a way I can count the number of words in a text box widget?  I realise that means counting the number of words in the attached variable - but can I do this?
    I have tried playing with Javascript (about which I know nothing)
    I put the script below into the script window for a button, but nothing seems to happen!
    Test=Q5WidgetAnswer.split(" ").length-1;
    document.write(Test);
    I want to check for three words in an answer and if there are only two, or four, warn that there are Three answers.
    Would be grateful for any help!

    After much heartache I solved the issue. 
    The code needed to be as follows:
    var objCP = document.Captivate;
    var Answer = objCP.cpEIGetValue('WidgetAnswer');
    var Words;
    if(Answer ==  ''){   /* tests for empty answer */
      Words=0;
    alert("Fred")
    else {
    Words = Answer.replace(/[^ ]/g,'').length+1;    /* counts the number of spaces in answer */
    Where objCP can be any name you want, and cpEISetValue and cpEIGetValue are special Captivate functions
    /* and */ enclose a comment

  • What happened to page count, word count and the toolbar at the top?

    Is there any way to edit the toolbar so that when I want to switch fonts I don't have to keep opening the toolbar on the side? (Is there anyway I can get the toolbar from the previous version back?)
    Also, is there a way for the page count and word count to show up and stay there for future documents? I had the word count appear and tried to save that as a template but when trying to open up new documents I have to go back and make it so the word count shows up again.

    What Peter said.
    Is there any way to edit the toolbar so that when I want to switch fonts I don't have to keep opening the toolbar on the side?
    Yes. Menu > View > Customize Toolbar... drag/drop the Fonts icon adjacent to the Comments icon on the Toolbar. The Fonts icon now becomes a toggle to show/hide the Fonts toolbox, which you could also produce with a command+T.
    (Is there anyway I can get the toolbar from the previous version back?
    No.
    Also, is there a way for the page count and word count to show up and stay there for future documents
    No. Available via Menu > View > Show Word Count. This produces a floating box at the bottom of your document. When you roll over it with your mouse, you have a selection of words, characters, and paragraphs. The word count excludes spaces.

  • Counting words, lines and char

    i want a program which counts the number of lines,words and characters in a file.....................
    please help me

    One thread is enough.Continue there, please.
    [http://forums.sun.com/thread.jspa?threadID=5367866]
    I'm locking this one.

  • Count words, but not in master pages...

    With this:
    var docWordCount = app.documents.everyItem().stories.everyItem().words.length; // words
    ... I count the words of all open documents.
    But how I can exclude the master pages?
    Thanks in advance ...!

    Well, I think I got what I wanted:
    var wMasters = app.documents.everyItem().masterSpreads.everyItem().textFrames.everyItem().words.length;var docWordCount = app.documents.everyItem().stories.everyItem().words.length; // words
    var myDocWordCount = docWordCount - wMasters;

  • Counting words within a file, please help!

    Hi i have written a program to read in a directories from inside another directory. I then want to count the files inside each of these directories.
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.nio.CharBuffer;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    public class CalculateMax {
              static int indentLevel = -1;
              static void ReadIn(File path) {
                List alist = new ArrayList();
                int count = 0;
                File files[];
                //keep track of directory level
                indentLevel++;
                files = path.listFiles();
                for (int i=0, n=files.length; i < n; i++) {
                  for (int indent=0; indent < indentLevel; indent++) {
                  System.out.println( files);
         try
         FileInputStream in1 = new FileInputStream(files[i]);
         FileChannel channel1 = in1.getChannel();
         int LengthOfFile1 = (int)channel1.size();
         MappedByteBuffer buffer1 = channel1.map(FileChannel.MapMode.READ_ONLY , 0, LengthOfFile1);
         Charset charset = Charset.forName("US-ASCII");
         //Transform the sequence of bytes in charset into Unicode characters.
         CharsetDecoder decoder = charset.newDecoder();
         CharBuffer charBuffer1 = decoder.decode(buffer1);
         Pattern endLine = Pattern.compile (".*$", Pattern.MULTILINE);
         Pattern wBreak = Pattern.compile ("[\\p{Digit}\\p{Punct}\\s]");
         Matcher matchLine1 = endLine.matcher(charBuffer1);
         while( matchLine1.find()) {
         CharSequence line1 = matchLine1.group();
         //Get the words in the line
         String words[] = wBreak.split(line1);
         for (int j = 0, k = words.length; j < k; j++) {
         if(words[j].length() > 0) {
         alist.add (words[j]);
         count++;
         catch(IOException ioe)
         System.err.println ("read error: " + ioe.getMessage());
    System.out.println("count : " + count);
         if (files[i].isDirectory()) {
         ReadIn(files[i]);
         indentLevel--;
         public static void main (String args[]) {
              ReadIn(new File("Data\\amy.smith\\"));
    The problem is that it seems to keeps reading in each inner directory as one files, so that the words in of every file in each directory are being added together instead of counting each seperately. Does anybody know where i am going wrong here? Any help would be greatly appreciated
    Thanks!

    Thanks! Im just after discovering a big problem with this method of reading the files however. I calling a method on each file i read in which returns an int value, what i need to then do is add together the ints within each directory, so for say:
    Data//amy.smith//file1.txt = 1
    Data//amy.smith//file2.txt = 5
    Data//amy.smith//file3.txt = 9
    it should return 15, but within the loop where the int value is returned i cannot find a way to add together only the ints within the same directory
    static void ReadDir(File path) {
                    int totals = 0;
                   int common = 0;
                File files[]; 
                indentLevel++;
                files = path.listFiles();
                for (int i=0, n=files.length; i < n; i++) {
                  for (int indent=0; indent < indentLevel; indent++) {
                   common = (findCommonWords(firstFile(),readFile(files)));
         words = totals(common, totalF1(), totalF2(files[i])));
         //add words together here for the files in each directory
         if (files[i].isDirectory()) {
         ReadDir(files[i]);
         indentLevel--; // and going up
         //System.out.println(list1);
    Does anybody know how i could do this. I would greatly appreciate any help
    Thanks

  • Help with program using hashtable to count words & other chars in txt file

    I need to use only a hashtable to count the occurences words and chars in a text file and display them alphabetically. I am not to use anything but the hashtable. so far, I can get it to count only the words in the file and not the chars, I want to know how to make it count the chars (,.;:?(){}[]!@#$%^&\t\"<>/`~ ) that may be found and if it is possible to get it to display them in a sorted (alphabetical) order w/o using anything else.
    This is what I have: mport java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane;
    class words{
    String word;
    int count;
    public class WordCount{
    static Hashtable h=new Hashtable();
    static words w;
    static void countWords(String s){
    if((w=(words)h.get((java.lang.Object)s))==null){
    w=new words();
    w.word=s;
    w.count=1;
    h.put(s,w);
    }else{
    w.count++;
    h.remove(s);
    h.put(s,w);
    public static void main(String args[]){
    String s;
    StringTokenizer st;
    String t;
    String fn = JOptionPane.showInputDialog("Enter the filename:");
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fn));
    s=br.readLine();
    while(s!=null){
    st= new StringTokenizer(s, " ,.;:?(){}[]!@#$%^&\t\"<>/`~  ");
    // Split your words.
    while(st.hasMoreTokens()){
    t=st.nextToken();
    countWords(t);
    s=br.readLine();
    }catch(Exception e){
    e.printStackTrace();
    Enumeration e=h.elements();
    w=(words)e.nextElement();
    while(e.hasMoreElements()){
    System.out.println(w.word + " " + w.count);
    w=(words)e.nextElement();
    System.exit(0);
    }

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

Maybe you are looking for