How to write a java program to take a person’s full name and display a surname with initials?

I wrote the following code. This works if there are only two initials before the name. How to change it to work with 3 or more initials. For instance:

Input: ABC EFG IJK XYZ

 Output I want is: AEI 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]); } } 
+6
source share
1 answer

Use a loop and do not limit the division 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]); } 
+3
source

Source: https://habr.com/ru/post/987365/


All Articles