Question 6
Write a program to accept a sentence and print only the first letter of each word of the
sentence in capital letters separated by a full stop.
Example:
INPUT SENTENCE:
OUTPUT:
“This is a cat”
T.I.A.C.
Answers
First Letter of each Word - Java
We will take user input through Scanner. For that, we import into the program. Then, we create a Scanner object and ask the user to input a sentence. The input is taken through the method.
We name the variable where we stored the input as . We now create a String type array, named by splitting the
We want to split the words through a whitespace. So, our method becomes . The resulting split items are stored in the array.
Now, we use the method to convert the words to upper case and extract the first character using .
We are now left with just printing these first characters with a fullstop.
FirstLetter.java
import java.util.Scanner;
public class FirstLetter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Create Scanner Object
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine(); //Take user input of sentence
String words[] = sentence.split(" "); //Split sentence into an array of words
for(int i=0; i<words.length; i++) {
//Convert each word to upper case and extract first character
char firstLetter = words[i].toUpperCase(). charAt(0);
//Print each letter and a fullstop
System.out.print(firstLetter+".");
}
}
}
Answer:
A program to accept a sentence and print only the first letter of each word of the sentence in capital letters separated by a full stop in JAVA is as follows:
import java . io . *;
class ini
{
public static void main ( ) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
String a;
char y;
int d;
System.out.print(" Please enter any sentence : ");
a=br . readLine( );
a=" "+a;
a=a . toUpperCase( );
d=a . length();
System. out. print("Output is = ");
for(int i=0; i<l ;i++)
{
x=a. charAt ( i );
if(x==' ')
System. out. print(a. charAt(i+1)+" . ");
}
}
}