Advertisements
Home > Java > Java Program to calculate number of characters, words and lines while reading from a input stream (file or console) – Q41

Java Program to calculate number of characters, words and lines while reading from a input stream (file or console) – Q41


Q41: Java Program to calculate number of characters, words and lines while reading from a input stream (file or console)

import java.io.*;

class WordCount{
	public static int words = 0;
	public static int lines = 0;
	public static int chars = 0;
	public static void wc(InputStreamReader isr) throws IOException{
		int c = 0;
		boolean lastWhite = true;
		String WhiteSpace = " \t\n\r";
		while((c = isr.read()) != -1){
			chars++;
			if(c == '\n')
				lines++;
			int index = WhiteSpace.indexOf(c);
			if(index == -1){
				if(lastWhite == true){
					++words;
				}
			lastWhite = false;
			}
			else
				lastWhite = true;
		}
		if(chars != 0)
			++lines;
	}
	public static void main(String args[]){
		FileReader fr;
		try{
			if(args.length == 0) {
				wc(new InputStreamReader(System.in));
			}
			
			else{
				for(int i=0; i<args.length; i++){
					fr = new FileReader(args[i]);
					wc(fr);
				}
			}
		}
		catch(IOException e){
			return;
		}
		System.out.println(lines + " " + words + " " + chars);
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: