In: Computer Science
Java please!
Write the code in Exercise.java to meet the following problem statement:
Write a program that will print the number of words, characters, and letters read as input. It is guaranteed that each input will consist of at least one line, and the program should stop reading input when either the end of the file is reached or a blank line of input is provided.
Words are assumed to be any non-empty blocks of text separated by spaces, and words will not cross over a line boundary. It is also assumed that there will be no whitespace characters before or after each line of input.
To determine if a character is a letter, use the Character.isLetter() static method.
EX:
input:
This is a sentence. There are 10 words in it.
output:
Words: 10
Characters: 44
Letters: 32
Short Summary:
Source Code:
package com.core.java;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/** This class reads input sentences from a file and prints the
no of words, characters and letters**/
public class StringOpsMain {
public static void main(String[] args) {
try {
//Get file input
using scanner
Scanner
input=new Scanner(new File("C:\\Users\\asus\\Input.txt"));
while(input.hasNext())
{
String sentence=input.nextLine();
//Stop reading input if a blank line is
found
if(sentence!=null&&sentence.length()>0)
calculateAndPrintChars(sentence);
else
break;
}
input.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
//This method prints the no of characters,letters and words in the
given input string
static void calculateAndPrintChars(String
sentence)
{
//Form a string array
String[]
sentenceArray=sentence.split(" ");
System.out.println("Input:\n"+sentence);
System.out.println("Output\nWords:"+sentenceArray.length);
int letterCount=0;
//Loop to find if its a
letter
for(int
i=0;i<sentence.length();i++)
{
if(Character.isLetter(sentence.charAt(i)))
letterCount++;
}
System.out.println("Characters:"+sentence.length());
System.out.println("Letters:"+letterCount);
}
}
Code Screenshot:
Output:
**************Please do upvote to appreciate our time.
Thank you!******************