User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 430,123 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,322 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 689 | Replies: 15 | Solved
Reply
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Stuck: Exception Handling and reading text from file

  #1  
Jun 26th, 2008
The task: Write a program that asks the user for a file and counts the number of characters, words, and lines in that file. Then the program asks for the name of the next file. When the user enters a file that doesn't exists, the program prints the total count of characters, words, and lines in all processed files and exits.

So far, when I run my code, my exception handling does not kick in if I try a random input name. When I input a correct file name, nothing happens.

My code:

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
/**
  * A class to count the number of characters, words, and lines in files.
  */

public class FileCounter
{
   /**
      Constructs a FileCounter object.
   */
   public FileCounter()
   {
    words = 0;
    lines = 0;
     
   }
   
   /**
      Processes an input source and adds its character, word, and line
      counts to this counter.
      @param in the scanner to process
   */
   public void read(Scanner console) throws FileNotFoundException
   {
       String input = console.next();
       FileReader reader = new FileReader(input);
       Scanner in = new Scanner(reader);

   }

   /**
      Gets the number of words in this counter.
      @return the number of words
   */
   public int getWordCount()
   {
     while (in.hasNextLine())
     {
     
     for(int i = 1; i <= in.nextLine().length(); i++)
     {
         int j = 0;
         if (in.nextLine().substring(j, i).equals(" "));
         words++;
         j++;
        }
    }
     return words;
   }

   /**
      Gets the number of lines in this counter.
      @return the number of lines
   */
   public int getLineCount()
   {
      
      while (in.hasNextLine())
      {
          lines++;
      }
      return lines;
    }

   /**
      Gets the number of characters in this counter.
      @return the number of characters
   */
   public int getCharacterCount()
   {
       //not worked on yet.
      return 0;
   }
   private Scanner in;
   private String input;
   private int words;
   private FileCounter counter;
   private int lines;
}

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

/**
  * This class prints a report on the contents of a number of files.
  *
 */

public class FileAnalyzer
{
   public static void main(String[] args)
      throws FileNotFoundException
   {
      Scanner in = new Scanner(System.in);
      FileCounter counter = new FileCounter();
      boolean more = true;
      System.out.print("Please enter the file name: ");
      while (more)
      {
        try
        {
            counter.read(in);
            
        }
        catch (FileNotFoundException exception)
        {
          
        
            System.out.println("Characters: " + counter.getCharacterCount());
            System.out.println("Words: " + counter.getWordCount());
            System.out.println("Lines: " + counter.getLineCount());
            more = false;
      
            
        }
      }
      
   }
}
AddThis Social Bookmark Button
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,870
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 284
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Maven

Re: Stuck: Exception Handling and reading text from file

  #2  
Jun 26th, 2008
The scanner that you are initializing in the read() method is not the same one the rest of the class is using. You have declared a new Scanner with the same name that is local just to that method
   public void read(Scanner console) throws FileNotFoundException
   {
       String input = console.next();
       FileReader reader = new FileReader(input);
       // This is not the same as your class-level "in" variable
       Scanner in = new Scanner(reader);

   }
Reply With Quote  
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Re: Stuck: Exception Handling and reading text from file

  #3  
Jun 27th, 2008
I changed the code to the following, with no luck. I think I'm doing something wrong when with the Scanner, but I'm not sure how to fix it. I continually get NullPointerException errors.

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
/**
 * Course Number: Comp 1123.
 * Assignment Number: 
 * Instructor: 
 * Question Number: 
 * A class to count the number of characters, words, and lines in files.
 * @author LevelSix
 * @version 
 */

public class FileCounter
{
   /**
      Constructs a FileCounter object.
   */
   public FileCounter()
   {
    words = 0;
    lines = 0;
    chars = 0;
    
   }
   
   /**
      Processes an input source and adds its character, word, and line
      counts to this counter.
      @param in the scanner to process
   */
   public void read(Scanner console) throws FileNotFoundException
   {
       String input = console.next();
       FileReader reader = new FileReader(input);
       in = new Scanner(reader);
       
       
   }

   /**
      Gets the number of words in this counter.
      @return the number of words
   */
   public int getWordCount()
   {
     
     boolean done = false;
     while (!done)
     {
         
         
     if (in.hasNextLine() == true)
     {
     for(int i = 1; i <= in.nextLine().length(); i++)
     {
         int j = 0;
         if (in.nextLine().substring(j, i).equals(" "));
         words++;
         
         j++;
     }
     }
     else
     {
         done = true;
     }
    }
    
     return words;
   }

   /**
      Gets the number of lines in this counter.
      @return the number of lines
   */
   public int getLineCount()
   {
       
     
      done = false;
      while (!done)
      {
        if(in.hasNextLine())
        lines++;
        else
        lines = 0;
  
      }
      return lines;
      
    }
    

   /**
      Gets the number of characters in this counter.
      @return the number of characters
   */
   public int getCharacterCount()
   {
       String file = in.next();
       char[] array = file.toCharArray();
       int num = array.length;
       chars += num;
       return chars;
   }
   private Scanner in;
   private String input;
   private int words;
   private FileCounter counter;
   private int lines;
   private boolean done;
   private int chars;
}
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,870
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 284
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Maven

Re: Stuck: Exception Handling and reading text from file

  #4  
Jun 27th, 2008
Well, those NullPointerExceptions tell you the variable that was null and the line it occurs on. Have you looked at those locations and tried to figure out why the variable is null when you use it?
Reply With Quote  
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Re: Stuck: Exception Handling and reading text from file

  #5  
Jun 27th, 2008
I get the exceptions at the first lines of the get count methods. I'm guessing it is because my Scanner is still null.
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,870
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 284
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Maven

Re: Stuck: Exception Handling and reading text from file

  #6  
Jun 27th, 2008
Sounds like a reasonable assumption. So now step through the code and determine why that scanner has not been initialized when you need to call it.

Consider that your read() method doesn't actually process anything. It just set's the scanner reference. You only call getWordCount() etc after read() has thrown an exception. Perhaps you should let getWordCount() and the other getX methods just return the current count values from the class and move the code that counts those things into countWords(), countX() methods and call those methods within read().
Last edited by Ezzaral : Jun 27th, 2008 at 4:10 pm.
Reply With Quote  
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Re: Stuck: Exception Handling and reading text from file

  #7  
Jun 28th, 2008
I decided to try and do my calculations purely in the read method, leaving the get methods to just return their respective values. I'm now getting a NoSuchElementException at the line that reads file=in.next();. I'm not sue what the issue is now.

The updated code:

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
/**
 * Course Number: Comp 1123.
 * Assignment Number: 
 * Instructor: 
 * Question Number: 
 * A class to count the number of characters, words, and lines in files.
 * @author LevelSix
 * @version 
 */

public class FileCounter
{
   /**
      Constructs a FileCounter object.
   */
   public FileCounter()
   {
    words = 0;
    lines = 0;
    chars = 0;
    
   }
   
   /**
      Processes an input source and adds its character, word, and line
      counts to this counter.
      @param in the scanner to process
   */
   public void read(Scanner console) throws FileNotFoundException
   {
       String input = console.next();
       FileReader reader = new FileReader(input);
       Scanner in = new Scanner(reader);
       boolean done = false;
       while (!done)
       {
           if (in.hasNextLine() == true)
           {
             lines++;
             while(in.hasNextLine())
             {
               int j = 0;
               int i = 1;
              file = in.next();
              if(file.substring(j, i).equals(" "))
              {
               words++;
              }
              else
              {
              words = 0;
            }
              j++;
              i++;
            }
         }
         else
         {
           done = true;
         }
       }
       
       char[] array = file.toCharArray();
       int num = array.length;
       chars += num;
       
   }

   /**
      Gets the number of words in this counter.
      @return the number of words
   */
   public int getWordCount()
   {
     return words;
   }

   /**
      Gets the number of lines in this counter.
      @return the number of lines
   */
   public int getLineCount()
   {    
      return lines;
   }    

   /**
      Gets the number of characters in this counter.
      @return the number of characters
   */
   public int getCharacterCount()
   {
       
       return chars;
   }
   
   private String input;
   private int words;
   private FileCounter counter;
   private int lines;
   private boolean done;
   private int chars;
   private String file;
}
Reply With Quote  
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Re: Stuck: Exception Handling and reading text from file

  #8  
Jul 1st, 2008
I've updated both pieces of code again. While I feel they are now closer to completion I'm getting strange happening during testing. If I input a non-existent file, the exception handling kicks in, no problem. If I enter a correct file, the virtual machine contiues to run, but it does not reprint the input line. I feel its safe to assume I have an infinite loop somewheres.

The updated code:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

/**
 * This class prints a report on the contents of a number of files
 */

public class FileAnalyzer
{
   public static void main(String[] args)
      throws FileNotFoundException
   {
      Scanner console = new Scanner(System.in);
      FileCounter counter = new FileCounter();
      boolean more = true;
      System.out.print("Please enter the file name: ");
      while (more)
      {
        
        try
        {
            String input = console.next();
            FileReader reader = new FileReader(input);
            Scanner in = new Scanner(reader);
            counter.read(in);
            
        }
        catch (FileNotFoundException exception)
        {
            more = false;
            System.out.println("Characters: " + counter.getCharacterCount());
            System.out.println("Words: " + counter.getWordCount());
            System.out.println("Lines: " + counter.getLineCount());
        }       
      }
      
   }
}

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
/**
 * A class to count the number of characters, words, and lines in files.
 */

public class FileCounter
{
   /**
      Constructs a FileCounter object.
   */
   public FileCounter()
   {
    words = 0;
    lines = 0;
    chars = 0;
    
   }
   
   /**
      Processes an input source and adds its character, word, and line
      counts to this counter.
      @param in the scanner to process
   */
   public void read(Scanner in) throws FileNotFoundException
   {
       
       boolean done = false;
       while (!done)
       {
             while(in.hasNextLine())
             {
               lines++;
               int j = 0;
               int i = 1;
              
               if(in.nextLine().substring(j, i).equals(" "))
               {
                 words++;
               }
               else
               {
                words = 0;
               }
               j++;
               i++;
               char[] array = in.nextLine().toCharArray();
               int num = array.length;
               chars += num;
               if(in.hasNextLine() == false)
               done = true;
            }
         }
         
       
   }

   /**
      Gets the number of words in this counter.
      @return the number of words
   */
   public int getWordCount()
   {
     return words;
   }

   /**
      Gets the number of lines in this counter.
      @return the number of lines
   */
   public int getLineCount()
   {    
      return lines;
   }    

   /**
      Gets the number of characters in this counter.
      @return the number of characters
   */
   public int getCharacterCount()
   {
       
       return chars;
   }
   
   private String input;
   private int words;
   private FileCounter counter;
   private int lines;
   private boolean done;
   private int chars;

}
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 567
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 64
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

Re: Stuck: Exception Handling and reading text from file

  #9  
Jul 1st, 2008
You can put the System.out.println() inside the while-loop:
while (more)
      {
        try
        {
            System.out.print("Please enter the file name: ");

            String input = console.next();
            FileReader reader = new FileReader(input);
            Scanner in = new Scanner(reader);
            counter.read(in);
            
        }
        catch (FileNotFoundException exception)
        {
            more = false;
            System.out.println("Characters: " + counter.getCharacterCount());
            System.out.println("Words: " + counter.getWordCount());
            System.out.println("Lines: " + counter.getLineCount());
        }       
      }

And then after the line: counter.read(in) , you should print the results. So when the while-loop repeats itself, you will be asked for a new file, and the results of the new file will be printed before the while tries to do another loop. And if you want to stop just enter a file that does not exist.

I don't think that you entered in an infinite loop. The program was just waiting for you to enter something, but since you didn't have any message before the console.next() , you didn't know that the program had stopped at that line and was waiting for your input.
I AM the 12th CYLON
Reply With Quote  
Join Date: May 2008
Posts: 44
Reputation: LevelSix is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
LevelSix's Avatar
LevelSix LevelSix is offline Offline
Light Poster

Re: Stuck: Exception Handling and reading text from file

  #10  
Jul 1st, 2008
Ahh, I didn't even notice that statement was outside the loop! So obvious now, thanks.
Well, the code finally runs as it should, except I guess my devices for calculating the number of characters, words and lines don't work as they should. Any suggestions on that part?

Also, I'm only supposed to print the results after a non-existent file has been entered. The results are supposed to refelect the total words, characters, and lines of all files processed.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Java Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Other Threads in the Java Forum

All times are GMT -4. The time now is 3:23 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC