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]);
}
}
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With