Name to Initial Version 2

Given a name the task is to convert the whole name except the last name to it’s initials.

Example: Consider a name “Netaji Subhas Chandra Bose”. The program should output “N. S. C. Bose”.

Java
import java.util.*;
public class NameInitial
{
    public static void main(String args[])
    {
        int l=0,cnt=0,flag=1;
        char ch=' ';
        String str="",nstr="",word="";
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a name: ");
        str=sc.nextLine();
        str=str.trim();
        str=str+" ";
        l=str.length();
        for(int i=0;i<l;i++)
        {
            ch=str.charAt(i);
            if(ch==' ')
            {
                cnt++;
            }
        }
        for(int i=0;i<l;i++)
        {
            ch=str.charAt(i);
            if(ch==' ')
            {
                if(flag==cnt)
                {
                    nstr=nstr+word+" ";
                }
                else
                {
                    nstr=nstr+word.charAt(0)+". ";
                }
                flag++;
                word="";
            }
            else
            {
                word=word+ch;
            }
        }
        System.out.println("Output String: "+nstr);
    }
}
Java