Write a program to input a sentence and convert it into uppercase and count and display the total number of words starting with a letter 'A'. Example: Sample Input: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING. Sample Output: Total number of words starting with letter 'A' = 4
Topic: Counting words beginning with a given letter
Answer
import java.util.Scanner;
class CountWordsA { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a sentence : "); String s = sc.nextLine().toUpperCase() + " ";
String word = ""; int count = 0; char ch;
for(int i = 0; i < s.length(); i++) { ch = s.charAt(i); if(ch == ' ') { if(word.length() > 0 && word.charAt(0) == 'A') count++; word = ""; } else word = word + ch; }
System.out.println("Total number of words starting with letter 'A' = " + count); } }
The word-extraction template again: build characters into a word until a space is met, then test the completed word.
Two details decide the marks. First, the trailing space added by + " " at the end of the input. Without it the LAST word never meets a space and is never tested — and in a sentence ending with a full stop, that word would be silently ignored. Adding the space is far simpler than handling the last word separately. Second, converting to uppercase FIRST means you only need to test against 'A', not against both 'A' and 'a'.
The test word.charAt(0) reads the first letter of the completed word; the guard word.length() > 0 protects against double spaces producing an empty word.
Trace the sample: ADVANCEMENT, AND, APPLICATION and ARE begin with A — four words, exactly as the question states. Note that CHANGING. keeps its full stop, which does not affect the first letter.
s String - the sentence in uppercase, with a trailing space word String - the word currently being built up ch char - holds each character of s in turn count int - number of words beginning with A i int - loop variable sc Scanner - object used to read input