Search code examples
javaexternalfile-handlingfile-read

Printing An External File's Contents


below is my code for a homework assignment where I need to read the contents of an external file and determine the number of words within it, number of 3-letter words, and percentage of total. I've got that part down just fine, but I also have to print the external file's contents prior to displaying the above information. Below is my current code:

public class Prog512h 
{
   public static void main( String[] args)
   {
    int countsOf3 = 0; 
    int countWords = 0; 

    DecimalFormat round = new DecimalFormat("##.00"); // will round final value to two decimal places

    Scanner poem = null;
    try 
    {
        poem = new Scanner (new File("prog512h.dat.txt"));
    }
    catch (FileNotFoundException e) 
    {
        System.out.println ("File not found!"); // returns error if file is not found
        System.exit (0);
    }

    while (poem.hasNext()) 
    { 
        String s = poem.nextLine(); 
        String[] words = s.split(" "); 
        countWords += words.length; 
        for (int i = 0; i < words.length; i++) 
        { 
            countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
        } 
    } 

    while(poem.hasNext()) 
    {       
        System.out.println(poem.nextLine());
    }
    System.out.println();
    System.out.println("Number of words: " + countWords); 
    System.out.println("Number of 3-letter words: " + countsOf3); 
    System.out.println("Percentage of total: " + round.format((double)((double)countsOf3 / (double)countWords) * 100.0)); // converts value to double and calculates percentage by dividing from total number of words
   } 

   }   

The statement

while(poem.hasNext()) 
{       
    System.out.println(poem.nextLine());
}

is supposed to print the external file's contents. However, it doesn't. When I try moving it before my prior while loop, it prints, but screws up my printed values for the # of words, 3-letter words, percentage, etc. I'm not really sure what the issue is here. Could someone provide some assistance?

Thank you in advance.


Solution

  • Your scanner is trying to reread the file but it is at the bottom so there are no more lines to read. You have two options:

    Option 1

    Create a new Scanner object for the same file (to start at the beginning again) and then call your while loop on that file (works, but not a great design).

    Scanner poem2 = null;
    try 
    {
        poem2 = new Scanner (new File("prog512h.dat.txt"));
    }
    catch (FileNotFoundException e) 
    {
        System.out.println ("File not found!"); // returns error if file is not found
        System.exit (0);
    }
    
    while(poem2.hasNext()) 
    {       
        System.out.println(poem2.nextLine());
    }
    

    Option 2

    A better option would be to display each line as you read it in. This can be accomplished by adding an extra line to the already existent while loop:

    while (poem.hasNext()) 
    { 
        String s = poem.nextLine();
        System.out.println(s); // <<< Display each line as you process it
        String[] words = s.split(" "); 
        countWords += words.length; 
        for (int i = 0; i < words.length; i++) 
        { 
            countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
        } 
    }
    

    This only requires one Scanner object and only requires one read-through of the file which is much more efficient.