Menu
Topics Index
...
`

Count - Java Example Program


Count
import java.io.*;

class Count
{
    public static void main(String arg[])
    {
        DataInputStream dis= new DataInputStream(System.in);
                System.out.println("Enter the file name");
                String str=dis.readLine();
                FileInputStream fis=new FileInputStream(str);
                int k,nc=0,nw=1,nl=1;
                while((k=fis.read())!=-1)
                {
                    char ch=(char)k;
                    if(ch==' '||ch=='\t'||ch=='\n') //LINE A
                        nw++;
                    if(ch=='\n')
                        nl++;
                    nc++;
                }
                System.out.println("no:of characters="+nc);
                System.out.println("no:of words="+nw);
                System.out.println("no:of lines="+nl);
                fis.close();
    
    }
}
OUTPUT

Enter the file name:
Sample.java
No:of characters=110
No:of words=21
no:of lines=8

DESCRIPTION

In this program , we demonstrate that counting the lines , words , characters of a file. Here in this program we take a sample.java file to count.

THINGS TO TRY
if u don’t place a null character in LINE A i.e.,
if(ch==' '||ch=='\t'||ch=='\n')
it shows an error called
empty character literal (or) unclosed character literal
check out this.

© meritcampus 2019

All Rights Reserved.

Open In App