Header Ads

Write a program in Java to accept a name(Containing three words) and Display only the initials (i.e., first letter of each word).

Sample Input : NARAYAN KUMAR DEY
Sample Output : N K D


Approach :

We have to get the index of first letter of each word and print that. Index of first letter of first word will always be zero and for the other words get the 'blank space + 1'. To do so we will search for the blank space in string using if statement.


Code :

import java.util.Scanner;
public class NameInitials {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a name of 3 or more words ");
String s = sc.nextLine();
int len = s.length();
System.out.print(s.charAt(0) + " ");
for (int i = 1; i < len; i++) {
char ch = s.charAt(i);
if (ch == ' ')
{
char cho = s.charAt(i+1);
System.out.print(cho + " ");
}
}
}
}


Output :

Enter a name of 3 or more words 
NARAYAN KUMAR DEY
N K D

Explanation :

Create a main method and scanner object then take a string input and calculate it's length. Print the character at 0 index i.e., the first letter of first word. To find another letters, create for loop from 1 to length of String and check each index for blank space using if statement. When the blank space is found, this means that previous word has ended and letter at next index will be the starting of next word. So print the character at i+1. Use print instead of println to print all the letters in same line, if println is used every character will be printed in new line.

Post a Comment

0 Comments