Dremendo Tag Line

Input a name and print its initials in Java

String - Question 4

In this question, we will see how to input a name and print its initials in Java programming. To know more about string click on the string lesson.

Q4) Write a program in Java to input a name and print its initials.

Example:
Input ->   MOHIT KUMAR AGARWAL
Output ->  M.K.A

Program

import java.util.Scanner;

public class Q4
{
    public static void main(String args[])
    {
        String s;
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a name");
        s=sc.nextLine();

        System.out.println("The initials of the name is");
        for(i=0; i<s.length(); i++)
        {
            if(i==0 && s.charAt(i)!=' ')
            {
                System.out.print(s.charAt(i));
            }
            else if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
            {
                System.out.print("."+s.charAt(i+1));
            }
        }
    }
}

Output

Enter a name
Mohandas Karamchand Gandhi
The initials of the name is
M.K.G
video-poster