简体   繁体   中英

Error while counting number of character,lines and words in java

i have written the following code to count the number of character excluding white spaces,count number of words,count number of lines.But my code is not showing proper output.

import java.io.*;

 class FileCount
{


public static void main(String args[]) throws Exception
{
    FileInputStream file=new FileInputStream("sample.txt");
    BufferedReader br=new BufferedReader(new InputStreamReader(file));
    int i;
    int countw=0,countl=0,countc=0;
    do
    {
        i=br.read();
        if((char)i==(' '))
            countw++;
        else if((char)i==('\n'))
            countl++;
        else 
            countc++;



    }while(i!=-1);
    System.out.println("Number of words:"+countw);
    System.out.println("Number of lines:"+countl);
    System.out.println("Number of characters:"+countc);
}
}

my file sample.txt has

hi my name is john
hey whts up

and my out put is

Number of words:6
Number of lines:2
Number of characters:26

You need to discard other whitespace characters as well including repeats, if any. A split around \\\\s+ gives you words separated by not only all whitespace characters but also any appearance of those characters in succession.

Having got a list of all words in the line it gets easier to update the count of words and characters using length methods of array and String .

Something like this will give you the result:

String line = null;
String[] words = null;
while ((line = br.readLine()) != null) {
    countl++;
    words = line.split("\\s+");
    countw += words.length;
    for (String word : words) {
        countc += word.length();
    }
}

A new line means also that the words ends. => There is not always a ' ' after each word.

  do
  {
  i=br.read();
    if((char)i==(' '))
        countw++;
    else if((char)i==('\n')){
        countl++;
        countw++;  // new line means also end of word
    }
    else 
        countc++;
}while(i!=-1);

End of file should also increase the number of words (if no ' ' of '\\n' was the last character. Also handling of more than one space between words is still not handled correctly.

=> You should think about more changes in your approach to handle this.

import java.io.*;

class FileCount {

    public static void main(String args[]) throws Exception {
        FileInputStream file = new FileInputStream("sample.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(file));
        int i;
        int countw = 0, countl = 0, countc = 0;
        do {
            i = br.read();
            if ((char) i == (' ')) { // You should also check for other delimiters, such as tabs, etc.
                countw++;
            }
            if ((char) i == ('\n')) { // This is for linux Windows should be different
                countw++; // Newlines also delimit words
                countl++;
            }  // Removed else. Newlines and spaces are also characters
            if (i != -1) {
                countc++; // Don't count EOF as character
            }


        } while (i != -1);


        System.out.println("Number of words " + countw);
        System.out.println("Number of lines " + countl); // Print lines instead of words
        System.out.println("Number of characters " + countc);
    }
}

Ouput:

Number of words 8
Number of lines 2
Number of characters 31

Validation

$ wc sample.txt 
2  8 31 sample.txt

Try this:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCount {
    /**
     *
     * @param filename
     * @return three-dimensional int array. Index 0 is number of lines
     * index 1 is number of words, index 2 is number of characters
     * (excluding newlines) 
     */
    public static int[] getStats(String filename) throws IOException {
        FileInputStream file = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(file));

        int[] stats = new int[3];
        String line;
        while ((line = br.readLine()) != null) {
            stats[0]++;
            stats[1] += line.split(" ").length;
            stats[2] += line.length();
        }

        return stats;
    }

    public static void main(String[] args) {
        int[] stats = new int[3];
        try {
            stats = getStats("sample.txt");
        } catch (IOException e) {
            System.err.println(e.toString());
        }
        System.out.println("Number of words:" + stats[1]);
        System.out.println("Number of lines:" + stats[0]);
        System.out.println("Number of characters:" + stats[2]);
    }

}

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