Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Word, Character And Line Count Program In Java
WhatsApp
Alagunila Meganathan
5y
15.4
k
0
2
25
Blog
WordCount.rar
Introduction
In this blog, I am going to explain the program for word, character and line count in Java.
Software Requirements
Java, Notepad.
Program
import
java.io.*;
public
class
WordCount {
private
static
void
linecount(String fName, BufferedReader in )
throws
IOException {
long
numChar =
0
;
long
numLine =
0
;
long
numWords =
0
;
String line;
do
{
line = in .readLine();
if
(line !=
null
) {
numChar += line.length();
numWords += wordcount(line);
numLine++;
}
}
while
(line !=
null
);
System.out.println(
"File Name: "
+ fName);
System.out.println(
"Number of characters: "
+ numChar);
System.out.println(
"Number of words: "
+ numWords);
System.out.println(
"Number of Lines: "
+ numLine);
}
private
static
void
linecount(String fileName) {
BufferedReader in =
null
;
try
{
FileReader fileReader =
new
FileReader(fileName); in =
new
BufferedReader(fileReader);
linecount(fileName, in );
}
catch
(IOException e) {
e.printStackTrace();
}
}
private
static
long
wordcount(String line) {
long
numWords =
0
;
int
index =
0
;
boolean
prevWhiteSpace =
true
;
while
(index < line.length()) {
char
c = line.charAt(index++);
boolean
currWhiteSpace = Character.isWhitespace(c);
if
(prevWhiteSpace && !currWhiteSpace) {
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return
numWords;
}
public
static
void
main(String[] args) {
long
numChar =
0
;
long
numLine =
0
;
String line;
try
{
if
(args.length ==
0
) {
BufferedReader in =
new
BufferedReader(
new
InputStreamReader(System.in));
line = in .readLine();
numChar = line.length();
if
(numChar !=
0
) {
numLine =
1
;
}
System.out.println(
"Number of characters: "
+ numChar);
System.out.println(
"Number of words: "
+ wordcount(line));
System.out.println(
"Number of lines: "
+ numLine);
}
else
{
for
(
int
i =
0
; i < args.length; i++) {
linecount(args[i]);
}
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
Output
Java
Word Count
Up Next
Prime Number Program Using Java With I/O Stream
Ebook Download
View all
Coding Principles
Read by 2.7k people
Download Now!
Learn
View all
Membership not found