Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a java program to accept the full name of a person and output the last name with initials?

Tags:

java

I've written the following code. This works if only there are two initials before last name. How do i modify it to work with 3 or more initials. For example:

Input: ABC EFG IJK XYZ

Output I want is: A E I XYZ

Here is my code:

import java.util.*;

class Name{
    public static void main(String[] args){
        System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        System.out.println(name);
        String[] arr = name.split(" ",3);
        System.out.println(arr[0].charAt(0)+" "+arr[1].charAt(0)+" "+arr[2]);
    }
} 
like image 577
coder123 Avatar asked Oct 19 '22 11:10

coder123


1 Answers

Use a loop and don't limit the split to 3 :

{
      System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
      Scanner sc = new Scanner(System.in);
      String name = sc.nextLine();
      System.out.println(name);
      String[] arr = name.split(" ");
      // print all the initials
      for (int i = 0; i < arr.length - 1; i++) {
          System.out.print(arr[i].charAt(0) + " ");
      }
      // print the last name
      System.out.println(arr[arr.length-1]);
}
like image 163
Eran Avatar answered Oct 29 '22 04:10

Eran