Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Counting Words in a File with a Loop

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Counting Words in a File with a Loop

    So the point of the program is to input a file and have the program generate the number of lines, characters, and words. As of right not I can generate the lines and the words. However, I cannot generate them both at the same time like when I need to because each method has its own loop. For this reason, which ever action I have second (in this case the loop to generate the number of lines) does not work. I was wondering how I could fix this and I'm also seeking advice on how to find the number of characters in the document.

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
     /**
      7     This program applies line numbers to a file.
      8  */
    public class LineNumberer
    {
    public static void main(String[] args) throws FileNotFoundException
    {
    // Prompt for the input and output file names
     
    Scanner console = new Scanner(System.in);
    System.out.print("Input file: ");
    String inputFileName = console.next();
     
    // Construct the Scanner and PrintWriter objects for reading and writing
    //C:\Users\Ben\Documents\NetBeansProjects\Ben\src\LineNumberer\test.txt
            File inputFile = new File(inputFileName);
    Scanner in = new Scanner(inputFile);
     
    int wordNumber = 1;
     
    while (in.hasNext())
    {
    String word = in.next();
     
       System.out.println(word);
       wordNumber++;
     
    }
     
     
    System.out.println("There are " + wordNumber + "Words");
     
     
     
    int lineNumber = 1;
     
    while (in.hasNextLine())
    {
    String line = in.nextLine();
    lineNumber++;
     }
     
     
    System.out.println("There are " + lineNumber + "Lines");
     
     
        }
     
    }


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    So either re-initialize your Scanner before each method or store the data in some kind of data structure that you can go back to without reading from the file again.

    And for counting the characters- how would you do that by hand? You know how to read in a line or a word, why not go from there?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    Hey thanks for the advice. For some reason I thought I couldn't change System in, I thought it needed to be together for whatever reason. So I got it so it can count the lines and words now. However, I'm still stick on counting the characters. I know I will be using the same format. I just don;t know of any in.next functions that count the characters.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    Quote Originally Posted by bengregg View Post
    Hey thanks for the advice. For some reason I thought I couldn't change System in, I thought it needed to be together for whatever reason. So I got it so it can count the lines and words now. However, I'm still stick on counting the characters. I know I will be using the same format. I just don;t know of any in.next functions that count the characters.
    Well, you know how to scan in a line. How would you count the characters of any other String?

    Or you could try changing the Scanner delimiter to read in every individual char. The API is your friend for that one.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    Lol, almost there.

    Here is what I have for the find Characters:

     
    File inputFileThree = new File(inputFileName);
    Scanner three = new Scanner(inputFileThree);
     
     
    int lineNumberAgain = 0;
     
     
    while (three.hasNextLine())
    {
     
    String lineagain = three.nextLine();
    int howLong = lineagain.length();
    System.out.println("There are " + howLong + " Characters");
    lineNumberAgain++;
    int Total = howLong + Total;
     
     
     }

    The only problem is that it says that Total has not been initialized. How can I initialize Total so that I can rewrite it everytime I add on howLong?

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    I'm not sure what your question is. What are you trying to do with lineNumberAgain? Isn't that similar to what you're trying to do with Total (which really should be total, by the way)?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    lineNumberAgain starts at the first line and for every loop it goes to the next line. The total is supposed to keep track of the total number of characters.

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    Quote Originally Posted by bengregg View Post
    lineNumberAgain starts at the first line and for every loop it goes to the next line. The total is supposed to keep track of the total number of characters.
    Right. That's almost the same thing though, so I don't know where you're having trouble.

    Hint: this line:

    lineNumberAgain++;

    is the same as doing this:

    lineNumberAgain = lineNumberAgain + 1;


    or this:

    lineNumberAgain += 1;
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    I know but the problem I am gaving is with int totalChars = lineChars + totalChar; (used to be int Total = howLong + Total;
    ) because it says that totalChars is not initiated. When I initiate totalChars = 0; above the loop I get the error that totalChars is already defined. How can I initiate totalChars so that the program runs and totalChars is updated everytime it goes through the loop and adds the lineChars?

  10. #10
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    Lol nevermind silly mistake I got it...
    int lineNumberAgain = 1;
     
    int totalChars=0;
    while (three.hasNextLine())
    {
    String lineagain = three.nextLine();
    int lineChars = lineagain.length();
    //System.out.println("There are " + lineChars + " Characters in Line " + lineNumberAgain);
    lineNumberAgain++;
    totalChars = lineChars + totalChars;
     
     }

    Thank you for all the help Kevin I appreciate it.

  11. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    Take a closer look at how you're doing lineNumberAgain. It's the same thing.

    Hint: how many times do you initialize lineNumberAgain? In other words, how many times do you have "int lineNumberAgain" in your code? And how many times are you trying to do that with totalChars?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  12. #12
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    But the program works none the less. Now I'm just working on separating the program into classes so it is object oriented.

    I have My getWords

     
    import java.util.Scanner;
     
    /**
     *
     * @author Ben
     */
    public class getWords {
     
    public int getWords(java.io.File aFile)
    {
    java.io.File file= aFile;
     
    Scanner one = new Scanner(file);
     
     
     
    int wordNumber = 0;
     
     
    while (one.hasNext())
    {
    String word = one.next();
       wordNumber++;
    }
     
    return wordNumber;
     
     
     
    }
    }

    and I'm trying to use

     
    File inputFileOne = chooser.getSelectedFile();
     
     
    getWords words = new getWords();
    getWords.getWords(inputFileOne);

    To call it from the main file

    It gives me the error non-static method getWords(java.io.File) cannot be referenced from a static content in the main file
    and unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown in getWords.

    I have never used an object as a parameter is it possible? How do I do it?
    Last edited by bengregg; February 8th, 2011 at 07:48 PM.

  13. #13
    Junior Member
    Join Date
    Feb 2011
    Location
    Philadelphia
    Posts
    16
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    SOLVE. LOL
    general form is
    sum=o;// initialized
    while ( condition)
    {
    ...
    sum= sum + num; // update the sum.
    count++ // keeps a count.
    ...
    }// end while loop

  14. #14
    Junior Member
    Join Date
    Feb 2011
    Location
    Philadelphia
    Posts
    16
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    not sure what u trying to do, but u need something like this.

    public static void main(String[] args) throws FileNotFoundException{
    Scanner inFile = new Scanner(new FileReader("File")); // reads from a file.
    PrintWriter outFile = new PrintWriter("File"); // Write on a file.
    }

  15. #15
    Junior Member
    Join Date
    Jan 2011
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    Lol I'm trying to seperate the program into classes now.
    The program works, it takes a file and counts the number of lines, words, and characters:

     
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import javax.swing.JFileChooser;
     /**
      7     This program applies line numbers to a file.
      8  */
    public class LineNumberer
    {
    public static void main(String[] args) throws FileNotFoundException
    {
    // Prompt for the input and output file names
     
    JFileChooser chooser = new JFileChooser();
    Scanner in = null;
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    {
        File inputFile = chooser.getSelectedFile();
        in = new Scanner(inputFile);
    }
     
     
     
     
    // Construct the Scanner and PrintWriter objects for reading and writing
    //C:\Users\Ben\Documents\NetBeansProjects\Ben\src\LineNumberer\test.txt
     
     
    File inputFileOne = chooser.getSelectedFile();
     
     
    getWords words = new getWords();
    getWords.getWords(inputFileOne);
     
     
     
     
    Scanner one = new Scanner(inputFileOne);
     
     
     
    int wordNumber = 0;
     
     
    while (one.hasNext())
    {
    String word = one.next();
     
     
       wordNumber++;
     
    }
     
     
    System.out.println("There are " + wordNumber + " Words");
     
     
     
     
     
     
     
    File inputFileTwo = chooser.getSelectedFile();
    Scanner two = new Scanner(inputFileTwo);
     
     
    int lineNumber = 0;
     
    while (two.hasNextLine())
    {
    String line = two.nextLine();
    lineNumber++;
     }
     
    System.out.println("There are " + lineNumber + " Lines");
     
     
     
     
     
     
    File inputFileThree = chooser.getSelectedFile();
    Scanner three = new Scanner(inputFileThree);
     
     
    int lineNumberAgain = 1;
     
    int totalChars=0;
    while (three.hasNextLine())
    {
    String lineagain = three.nextLine();
    int lineChars = lineagain.length();
    //System.out.println("There are " + lineChars + " Characters in Line " + lineNumberAgain);
    lineNumberAgain++;
    totalChars = lineChars + totalChars;
     
     }
     
    System.out.println("There are " + totalChars + " Total Characters");
     
    //C:\Temp\Test.txt
     
     
     
     
        }
     
    }

    Now I'm trying to get the program to work in an object oriented manor. So I am breaking up the methods and putting them in separate classes (getWords, getLines, getCharacters)

    I am stuck on the first method because I am trying to use the object use another object as a parameter:

     
    File inputFileOne = chooser.getSelectedFile();
     
     
    getWords words = new getWords();
    getWords.getWords(inputFileOne);

    And it is not working as I stated above

  16. #16
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    Quote Originally Posted by bengregg View Post
    And it is not working as I stated above
    Sorry, but how is it not working? Are you getting an Exception? If so, give us the exact stack trace, pointing out any line numbers so we don't have to count. Also, it'd be nice if you could trim this up a little more- boil it down to an SSCCE that demonstrates the problem in as few lines as possible.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  17. #17
    Junior Member
    Join Date
    Dec 2008
    Location
    london
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Counting Words in a File with a Loop

    read the file character by charecter upto EOF. if any of the character is equal to the ' ' single space or EOF increase the wordcount value by one
    paruchuri

  18. #18
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Counting Words in a File with a Loop

    Quote Originally Posted by vigneswara View Post
    read the file character by charecter upto EOF. if any of the character is equal to the ' ' single space or EOF increase the wordcount value by one
    Why in the world would you do it this way, when there are functions available for reading files word by word? For example, what happens with your algorithm if there are two spaces in a row? Or weird/incorrect punctuation?

    Please don't give out wrong advice.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Need help.. Counting Prime #'s up to 50 w/while loop
    By stommy989 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 6th, 2010, 05:40 PM
  2. counting words of a text file
    By maybach230 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: May 6th, 2010, 03:40 PM
  3. Counting Vowels and Prepositions in a text file
    By maybach230 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 27th, 2010, 07:36 PM
  4. Help: Num to words
    By shamed in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 7th, 2010, 06:55 PM
  5. Adding Marathi words to MySQL table
    By vaishali in forum JavaServer Pages: JSP & JSTL
    Replies: 3
    Last Post: July 8th, 2009, 06:43 AM