简体   繁体   中英

Error in counting number of words and characters from a file in java

I have written the following code to print file content and print the number of character and words from file

import java.io.*;
import java.util.*;

 class Ass53
{ 


public static void main(String args[]) throws Exception
{
    File file=new File("sample.txt");
    Scanner sc=new Scanner(new FileInputStream(file));
    String line,line1;
    int count1=0;
    int count=0;        

    /*Loop for printing contents of file*/
    while(sc.hasNextLine())
    {
        line=sc.nextLine();
        System.out.println(line);
    }


    /*loop for counting number of character in file*/
    while(sc.hasNext())
    {
            line1=sc.next();
        for(int i=1;i<=line1.length();i++)
            count1++;
    }
    System.out.println(count1); 


    /*loop for counting number of words in a file*/
    while(sc.hasNext())
    {
            sc.next();
            count++;
    }
    System.out.println("Number of words: " + count);


    }


 }

The problem is that only first while loop is executing.I guess the reason may be the sc.nextLine for first while loop.After first while loop sc points to nothing i guess?.

Is there any way to fix it? I want that my other while loop also work

Every time you are doing nextLine() you are advancing the scanner past the current line. When the first loop is over, you are at the end of the file and there is nothing to scan.

A solution would be to recreate the scanner before each loop. Just repeat this before second and third while :

sc=new Scanner(new FileInputStream(file));

Another solution would involve more work but is more elegant: use a single loop to store all lines in a List<String> , then analyse all lines to count words and characters.

You need to set your sc back to the beginning of the stream after you're done looping over it each time.

I won't post the code because this looks like homework, and I'm guessing the class name Ass53 is "Assignment53". It shouldn't be too hard to look up and figure out how to set the stream back to the beginning.

Of you could try to combine this into a single loop, because as it stands right now, you're actually reading the same file 3 times. It might not be that bad if it's a small file, but if it's a larger file that would be slow.

The first loop say "until I run out of lines in the file, read the line and print it." Then the second loop looks for more characters in the file, and of course there's nothing there.

One option is to reset the scanner before each loop. Before each loop after the first, just close and discard the scanner, and create a new one.

There's a better way, though. You can walk through the file character-by-character (eg with a BufferedReader ), and increment the character count on each character, and the newline count on each newline character. Don't forget to account for files that don't end with a newline. Only one loop is required, and you've calculated both the total character count and the line count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM