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;
      
            
        }
      }
      
   }
}

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);
       [B]// This is not the same as your class-level "in" variable[/B]
       [B]Scanner in = new Scanner(reader);[/B]

   }

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;
}

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?

I get the exceptions at the first lines of the get count methods. I'm guessing it is because my Scanner is still null.

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().

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;
}

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;

}

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.

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, or at least, as I thought they would. 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 reflect the total words, characters, and lines of all files processed.

I will have to take a better look on your code then for your last question:

my devices for calculating the number of characters, words and lines don't work as they should, or at least, as I thought they would. Any suggestions on that part?

Try to use files with one word and one line and see if it works.
Then files with one line and many words.

Try to test simple cases first and see how they behave.

The line counting works fine. The word counter skips directly to the else, and ends. I believe this is because its only checking one substring, not all of them.

Correct. You aren't processing all of the text within the line, you are merely looking at one location and then moving on to the next line.

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;
      
            
        }
      }
      
   }
}

You can try to use try/catch under your read function. and throw an exception when file not found. Like
Under read function

try{
String input = console.next();
FileReader reader = new FileReader(input);
Scanner in = new Scanner(reader);
}
catch(FileNotFoundException ex){
throw FileNotFoundException;
}

Also check: reading from console is right:

Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String login = c.readLine("Enter your login: ");

I think i finally completed the code. It seems to be working correctly now. I'll post it below and if anyone could take a look and see if there are any further errors I would appreciate it. Thanks for the help.

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;
    input = "";
    
   }
   
   /**
      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++;
               words++;
               int j = 0;
               file = in.nextLine();
               input = input + file;
               for(int i = 1; i < file.length(); i++)
               {
               if(file.substring(j, i).equals(" "))
               {
                 words++;
               }
               
               
               j++;
              
            }
              }
               char[] array = input.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;
   private String file;

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.