write a program in Java to accept a name and display the initial along with the surname
Answers
Answer:
When the full name is provided, the initials of the name are printed with the last name is printed in full. An example of this is given as follows −
Full name = Amy Thomas
Initials with surname is = A. Thomas
A program that demonstrates this is given as follows −
Example
Live Demo
import java.util.*;
public class Example {
public static void main(String[] args) {
String name = "John Matthew Adams";
System.out.println("The full name is: " + name);
System.out.print("Initials with surname is: ");
int len = name.length();
name = name.trim();
String str1 = "";
for (int i = 0; i < len; i++) {
char ch = name.charAt(i);
if (ch != ' ') {
str1 = str1 + ch;
} else {
System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
str1 = "";
}
}
String str2 = "";
for (int j = 0; j < str1.length(); j++) {
if (j == 0)
str2 = str2 + Character.toUpperCase(str1.charAt(0));
else
str2 = str2 + Character.toLowerCase(str1.charAt(j));
}
System.out.println(str2);
}
}
Output
The full name is: John Matthew Adams
Initials with surname is: J. M. Adams
Now let us understand the above program.
The name is printed. Then the first letter of the name is printed i.e. the initials. The code snippet that demonstrates this is given as follows −
String name = "John Matthew Adams";
System.out.println("The full name is: " + name);
System.out.print("Initials with surname is: ");
int len = name.length();
name = name.trim();
String str1 = "";
for (int i = 0; i < len; i++) {
char ch = name.charAt(i);
if (ch != ' ') {
str1 = str1 + ch;
} else {
System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
str1 = "";
}
}
Then, the entire surname of the name is printed. The code snippet that demonstrates this is given as follows −
String str2 = "";
for (int j = 0; j < str1.length(); j++) {
if (j == 0)
str2 = str2 + Character.toUpperCase(str1.charAt(0));
else
str2 = str2 + Character.toLowerCase(str1.charAt(j));
}
System.out.println(str2);
Explanation:
please thank my answer