Dremendo Tag Line

Input a name and print the initial along with title in Java

String - Question 5

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

Q5) Write a program in Java to input a name and print the initial first and then the title.

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

Program

import java.util.Scanner;

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

        System.out.println("Enter a name");
        s=sc.nextLine();
        ls=s.lastIndexOf(' ');		// finding the last space position

        System.out.println("The initials and the title is");
        for(i=0; i<ls; 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)+".");
            }
        }

        // printing the title from the last space onwards
        System.out.println(s.substring(ls));
    }
}

Output

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